Chapter 7
Chapter 7
Handling
7.1 Functions in Python
A function is a reusable block of code that performs a specific task.
Syntax:
python
Copy
def function_name(parameters):
# function body
return value # (optional)
Example:
python
Copy
def greet(name):
return "Hello, " + name
python
Copy
greet("Bob")
Example:
python
Copy
def add(a, b=5): # Default argument
return a + b
print(add(3)) # Output: 8
print(add(3, 7)) # Output: 10
print(square(4)) # Output: 16
python
Copy
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
Example:
python
Copy
x = 50 # Global Variable
def func():
x = 10 # Local Variable
print(x) # Output: 10
func()
print(x) # Output: 50
Python can read and write files using file handling operations.
python
Copy
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
python
Copy
file = open("example.txt", "r")
lines = file.readlines()
for line in lines:
print(line.strip()) # Removes extra newline
file.close()
Example:
python
Copy
with open("example.txt", "r") as file:
content = file.read()
print(content)
# No need for file.close()
Summary of Chapter 7
Functions → Reusable blocks of code.
Types of Functions → Built-in, User-defined, Recursive.
Arguments → Positional, Default, Keyword, Variable-length.
Scope → Local and Global variables.
File Handling → Read, Write, Append modes.
File Methods → read(), write(), readlines().
Exception Handling → Prevents file-related errors.