Errors (exceptions)
When something goes wrong, Python stops and shows an error. Dividing by zero is a classic:
print(10 / 0)
ZeroDivisionError: division by zero
To keep the program running, wrap risky code in try and say what to do in except.
try:
number = int("abc")
print(number)
except ValueError:
print("That was not a number")
print("The program keeps going")
Output:
That was not a number
The program keeps going
A friendly input loop that keeps asking until it gets a valid number (run it on your own computer):
while True:
try:
age = int(input("Your age: "))
break
except ValueError:
print("Please type digits only")
print("Thank you")
Writing a file
open(name, "w") opens a file for writing (it replaces anything already there). Using with closes the file for you automatically.
with open("marks.txt", "w") as f:
f.write("Sita,72\n")
f.write("Ram,85\n")
print("saved")
Output:
saved
Reading a file
with open("marks.txt", "w") as f:
f.write("Sita,72\nRam,85\n")
with open("marks.txt") as f:
for line in f:
name, marks = line.strip().split(",")
print(name, int(marks) + 5)
Output:
Sita 77
Ram 90
Use
"a"instead of"w"to append to the end of a file without erasing it. If a file might not exist, catchFileNotFoundError.
Try it yourself
- Write a program that saves three of your friends' names to a file, one per line.
- Read the file back and print each name in capitals.
- Wrap your reading code in try/except so a missing file prints a friendly message.
Next lesson: put everything together in a mini project.

Comments
Loading comments…