Python Programming-5
(Nested Loops, Exception Handling, File
- IO)
Books
Agenda
1. Nested Loops
2. Exception Handling
3. File IO
Nested Loops
1. A nested loop is a loop inside another for i in range(3):
loop. for j in range(2):
2. The inner loop runs completely for print(f"i={i}, j={j}")
each iteration of the outer loop.
Nested Loops - Use Case
1. Used in matrix operations. for i in range(3):
2. Common in data processing. for j in range(2):
3. Helps in solving complex problems print(f"i={i}, j={j}")
efficiently.
Nested Loops - Example
rows = 5
for i in range(1, rows+1):
for j in range(i):
print("*", end=" ")
print()
Nested Loops - Example
Processing a 2D List (Matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for col in row:
print(col, end=" ")
print()
Exception Handling
1. Exceptions are errors detected during try:
execution. num = int(input("Enter a number: "))
2. Use try, except, and finally to handle print(10 / num)
except ZeroDivisionError:
exceptions gracefully.
print("Cannot divide by zero!")
except ValueError:
print("Invalid input! Enter a number.")
finally:
print("Execution completed.")
Exception Handling - Types
1. ZeroDivisionError: Division by zero. try:
2. ValueError: Invalid input type. lst = [1, 2, 3]
3. IndexError: Accessing out-of-range list elements. print(lst[5])
except IndexError as e:
4. FileNotFoundError: Trying to open a non-existent file.
print(f"Error: {e}")
5. KeyError: Accessing a non-existent key in a dictionary.
Exception Handling - Example
while True:
try:
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative.")
break
except ValueError as e:
print(f"Invalid input: {e}")
File I/O - Introduction
[Link]
[Link]#open
1. File operations allow reading and writing data to files.
file = open("[Link]", "w")
1. Modes: [Link]("Hello, File I/O!")
r - Read
[Link]()
w - Write
a - Append
r+ - Read and Write
File I/O - Reading Files
with open("[Link]", "r") as file:
content = [Link]()
print(content)
with open("[Link]", "r") as file:
for line in file:
print([Link]())
File I/O - Writing & Appending
with open("[Link]", "w") as file:
[Link]("Python File Handling\n")
with open("[Link]", "a") as file:
[Link]("Appending new data\n")
Home Task:
You are developing a simple student record system for a Task 1: Display All Student Names
school. The system stores student names in a text file named
[Link]. Your task is to create a Python program that 1. Open [Link] in read mode and
allows users to: display its contents.
1. View all student names 2. Handle cases where the file is missing.
2. Add a new student name
3. Handle errors if the file is missing or inputs are invalid
Task 2: Add a New Student Name
Hint: Use readlines function in open, ‘a’ append mode 1. Allow the user to enter a new student
name.
Steps:
2. Append it to [Link].
1. Manually create a file named [Link] in the same 3. If [Link] is missing, show an error
folder as your Python script. message.
2. Add some sample student names, each on a new line.