0% found this document useful (0 votes)
7 views5 pages

Chapter 7

Chapter 7 covers Python functions, including their types (built-in, user-defined, recursive) and how to define and call them with various argument types (positional, default, keyword, variable-length). It also discusses variable scope (local and global), file handling operations (read, write, append), and methods for file manipulation, as well as exception handling to manage file-related errors. The chapter emphasizes the importance of functions and file handling in Python programming.

Uploaded by

ashim05birbhum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views5 pages

Chapter 7

Chapter 7 covers Python functions, including their types (built-in, user-defined, recursive) and how to define and call them with various argument types (positional, default, keyword, variable-length). It also discusses variable scope (local and global), file handling operations (read, write, append), and methods for file manipulation, as well as exception handling to manage file-related errors. The chapter emphasizes the importance of functions and file handling in Python programming.

Uploaded by

ashim05birbhum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Chapter 7: Python – Functions & File

Handling
7.1 Functions in Python
A function is a reusable block of code that performs a specific task.

7.1.1 Types of Functions

1. Built-in Functions → Predefined functions (e.g., len(), print(), max()).


2. User-Defined Functions → Functions created by the programmer.

7.1.2 Defining a Function

Syntax:

python
Copy
def function_name(parameters):
# function body
return value # (optional)

Example:

python
Copy
def greet(name):
return "Hello, " + name

print(greet("Alice")) # Output: Hello, Alice

7.1.3 Calling a Function

A function is called using its name followed by parentheses:

python
Copy
greet("Bob")

7.2 Function Parameters & Arguments


7.2.1 Types of Arguments

Type Description Example


Positional Arguments Values passed in order. greet("Alice")
Assigns a default value if not def
Default Arguments greet(name="Guest")
provided.
Type Description Example
Keyword Arguments Specifies parameters by name. greet(name="Charlie")
Variable-Length def sum(*numbers):
Allows multiple arguments.
Arguments

Example:

python
Copy
def add(a, b=5): # Default argument
return a + b

print(add(3)) # Output: 8
print(add(3, 7)) # Output: 10

7.3 Types of Functions


7.3.1 Functions without Return Value
python
Copy
def greet():
print("Hello, World!")

7.3.2 Functions with Return Value


python
Copy
def square(num):
return num * num

print(square(4)) # Output: 16

7.3.3 Recursive Functions

A function that calls itself.

python
Copy
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)

print(factorial(5)) # Output: 120

7.4 Scope & Lifetime of Variables


7.4.1 Local & Global Variables
Variable Type Scope Example
Local Variable Exists inside a function only. def func(): x = 10
Global Variable Available throughout the program. x = 100

Example:

python
Copy
x = 50 # Global Variable

def func():
x = 10 # Local Variable
print(x) # Output: 10

func()
print(x) # Output: 50

7.5 File Handling in Python


7.5.1 Introduction to File Handling

Python can read and write files using file handling operations.

7.5.2 File Operations

Mode Symbol Description


Read r Opens file for reading (default mode).
Write w Opens file for writing (erases existing content).
Append a Opens file for appending (adds to the end).
Read & Write r+ Reads and writes to a file.
Binary rb, wb, ab Reads/writes in binary mode.

Example (Opening a file in read mode):

python
Copy
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

7.6 Reading & Writing Files


7.6.1 Writing to a File
python
Copy
file = open("example.txt", "w")
file.write("Hello, Python!")
file.close()

 If the file doesn’t exist, it will be created.


 If the file exists, old content is deleted.

7.6.2 Reading from a File


python
Copy
file = open("example.txt", "r")
print(file.read()) # Reads entire file content
file.close()

7.6.3 Appending to a File


python
Copy
file = open("example.txt", "a")
file.write("\nNew line added.")
file.close()

 Appends data instead of overwriting existing content.

7.7 Working with File Methods


Method Description
read() Reads the entire file.
readline() Reads a single line from the file.
readlines() Reads all lines into a list.
write() Writes data to the file.
writelines() Writes multiple lines from a list.

Example (readlines() method):

python
Copy
file = open("example.txt", "r")
lines = file.readlines()
for line in lines:
print(line.strip()) # Removes extra newline
file.close()

7.8 Using with Statement for File Handling


The with statement automatically closes the file after use.

Example:
python
Copy
with open("example.txt", "r") as file:
content = file.read()
print(content)
# No need for file.close()

7.9 Handling Exceptions in File Operations


If a file does not exist, attempting to read it will cause an error.

7.9.1 Handling Errors Using try-except


python
Copy
try:
file = open("nonexistent.txt", "r")
print(file.read())
except FileNotFoundError:
print("File not found!")

 Prevents the program from crashing if the file is missing.

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.

You might also like