Functions and File Handling in Python
In Python, functions and file handling are essential aspects of programming, allowing developers to organize code logically, manage resources, and work with data files efficiently. Here, we’ll explore the basics of Python functions, inbuilt functions like `id`, `len`, `chr`, `ord`, and delve into file handling techniques, including defining, using, and manipulating files in Python.
Functions in Python
Functions are reusable blocks of code that perform a specific task. Using functions, we can split our code into smaller, manageable parts, making it easier to debug, test, and maintain. Functions in Python can be user-defined or inbuilt.
Defining and Calling a Function
In Python, a function is defined using the `def` keyword followed by a function name, parentheses, and a colon.
def greet(name):
print("Hello, " + name + "!")
greet("Vivek")
In the example above, `greet()` is a simple function that takes one argument, `name`, and prints a greeting message.
Arguments in Functions
Python functions can have multiple arguments, and these can be passed as required, default, keyword, or variable-length arguments.
- Positional Arguments: Order matters.
- Keyword Arguments: Specify arguments by name.
- Default Arguments: Default value if not provided.
- Variable-length Arguments: Use `*args` or `**kwargs`.
def add_numbers(a, b=5):
return a + b
print(add_numbers(3)) #Output: 8
Global vs. Local Variables
Variables defined inside a function are local to that function and cannot be accessed outside of it. Global variables, however, are accessible throughout the script.
x = 10 #Global variable
def example():
x = 5 #Local variable
print("Local x:", x)
example()
print("Global x:", x)
Lambda Functions
Lambda functions are small, anonymous functions defined using the `lambda` keyword. They can have any number of arguments but only one expression. Commonly used for short-term operations.
square = lambda x: x * x
print(square(5)) #Output: 25
Inbuilt Functions: `id`, `len`, `chr`, `ord`
1. `id()`: Returns the memory address of an object.
2. `len()`: Returns the length of a collection.
3. `chr()`: Converts an ASCII code to its corresponding character.
4. `ord()`: Converts a character to its ASCII code.
Example:
print(id(10)) # Memory address of integer 10
print(len("Python")) # Length of the string "Python"
print(chr(65)) # ASCII to character (Output: 'A')
print(ord('A')) # Character to ASCII (Output: 65)
Using `map()`, `filter()`, and `reduce()` Functions
1. `map()`: Applies a function to every item in an iterable (e.g., list).
2. `filter()`: Filters elements based on a function that returns a Boolean.
3. `reduce()`: Reduces an iterable to a single value using a specified function. It requires importing from `functools`.
from functools import reduce
# Example with map
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x * x, numbers))
print(squared) # Output: [1, 4, 9, 16]
# Example with filter
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4]
# Example with reduce
sum_total = reduce(lambda x, y: x + y, numbers)
print(sum_total) # Output: 10
File Handling in Python
File handling in Python allows us to create, read, write, and close files. Python provides built-in functions like `open()`, `write()`, `read()`, and `close()` for managing files.
Opening a File
To open a file, use `open()` with the file name and mode (`'r'` for reading, `'w'` for writing, `'a'` for appending).
file = open("example.txt", "w") # Opens file in write mode
file.write("Hello, Python!") # Writes to file
file.close() # Closes the file
Reading a File
You can read a file’s contents using `read()`, `readline()`, or `readlines()`.
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
Example Code: Functions and File Handling in Python
Here's an example that demonstrates both functions and file handling in Python:
# Function to write data to a file
def write_to_file(filename, text):
with open(filename, 'w') as file:
file.write(text)
print(f"Data written to {filename}")
# Function to read data from a file and display its content
def read_from_file(filename):
try:
with open(filename, 'r') as file:
content = file.read()
print("File content:", content)
except FileNotFoundError:
print("The file does not exist.")
# Using the functions
write_to_file("sample.txt", "Welcome to Python file handling!")
read_from_file("sample.txt")
In this example, the `write_to_file` function writes a string to `sample.txt`, while `read_from_file` reads and prints its contents.
Conclusion
Functions and file handling are powerful aspects of Python programming. By mastering functions, developers can create modular, efficient code, and by understanding file handling, they can work seamlessly with external data files. Whether it’s working with lambda functions, inbuilt functions like `id`, `len`, `chr`, and `ord`, or utilizing advanced techniques like `map`, `filter`, and `reduce`, Python provides the tools needed to write effective and organized code.
Comments
Post a Comment