Unit 3: FUNCTIONS and FILES
FUNCTIONS
Definition of Function:
A function is a reusable block of code that performs a specific task. It helps break programs into
smaller, manageable parts.
Types of Functions:
1. Built-in Functions: Already available in Python.
Examples: print(), len(), type(), sum(), etc.
2. User-defined Functions: Created by the programmer using the def keyword.
Syntax:
Function Parameters & Arguments
1. Positional Arguments:
● Matched by position (order).
2. Keyword Arguments:
● Matched by name.
3. Default Arguments:
● Assigns default values to parameters.
*4. Arbitrary Arguments (args):
Used when the number of arguments is unknown. Arguments are stored as a tuple.
**5. Arbitrary Keyword Arguments (kwargs):
Used when keyword arguments are unknown; stored as a dictionary.
Scope of Variables:
1. Local Scope:
Variables defined inside a function. Accessible only within that function.
2. Global Scope:
Variables defined outside any function. Can be accessed from anywhere.
3. Using global Keyword:
Used to modify a global variable inside a function.
Recursion:
A function that calls itself.
Example: Factorial using Recursion
Use cases: Mathematical operations like factorial, Fibonacci, tree traversal, etc.
Lambda Functions:
An anonymous (unnamed) function written using the lambda keyword. Generally used for short
functions.
Can be used with map(), filter(), and reduce().
FILES
File Handling:
● Used to read/write data from/to files using Python's built-in functions.
Steps:
1. Open the file
2. Perform read/write
3. Close the file
1. Opening a File:
Modes:
● 'r' – Read (default)
● 'w' – Write (creates new or overwrites)
● 'a' – Append
● 'r+' – Read and write
2. Reading from a File:
3. Writing to a File:
Appending to a File:
Closing a File:
● Always close the file after use.
Tell and Seek Methods:
tell():
● Returns the current file cursor position.
seek(offset):
● Moves the file cursor to a specific position.
CODE FOR WRITE, READ and APPEND FILES
1. Writing to a File (Overwrites if file exists)
2. Reading from a File
3. Appending to a File (Adds content at the end)
4. Deleting a File
● Notes:
○ os.path.exists(filename) ensures that the file exists before attempting to delete it.
○ os.remove(filename) deletes the file permanently from the directory.
○ If you try to delete a file that doesn't exist without this check, Python will raise a
FileNotFoundError.