Server Info & Course Info
open("non_existent_file.txt")
# Like searching for classroom 404 that doesn't exist
total_people = 0
cake_slices = 8 / total_people
# Like preparing cake slices when no one comes to party
while True
print(new_variable)
1+'a'
fi=open('okokokokok.txt','r')
while True:
print('yes')
python3 demo.py
Traceback (most recent call last):
File "demo.py", line 3, in <module>
print(undefined_var)
NameError: name 'undefined_var' is not defined
def greet():
print("Hello!") # Missing indentation
greet()
age = "20"
years_to_drive = age - 16
try:
# Code that might fail
result = 10 / 0
except ZeroDivisionError:
print("Oops! Can't divide by zero!")
try: Contains risky codeexcept: Handles specific errorsWhat if someone tries to calculate BMI with zero height?
try:
weight = 70
height = 0
bmi = weight / height
except ZeroDivisionError:
print("Alert! Did you enter height as zero?")
What if student list file is missing?
try:
with open("ghost_file.txt") as f:
print(f.read())
except FileNotFoundError:
print("Pssst... this file doesn't exist!")
FileNotFoundError specific handlerWhen you’re not sure what might go wrong:
try:
magic_number = "100" + 5
except Exception as e:
print(e)
Exception catches all errorsas e stores error detailsMake technical errors human-friendly:
try:
user_age = int(input("Enter age: "))
except ValueError:
print("Hey! Numbers only please :)")
try:
guests = int(input("Number of guests: "))
1+'2'
sugar_per_person = 50
total_sugar = sugar_per_person * guests
print("Needed sugar: "+str(total_sugar)+"g")
except ValueError:
print("Numbers only for guests please!")
except Exception as e:
print(e)
try:
num = int(input("Enter number: "))
except ValueError:
print("Numbers only please!")
try:
age = int(input("Age: "))
print(str(100/age))
except ValueError:
print("Numbers only!")
except ZeroDivisionError:
print("Age can't be zero!")
ValueErrorZeroDivisionErrortry:
with open("grades.txt") as f:
print(f.read())
except (FileNotFoundError, PermissionError):
print("File problem! Check if:")
print("- File exists")
print("- You have access")
try:
total = float(input("Total points: "))
earned = float(input("Earned points: "))
percentage = (earned/total)*100
except ValueError:
print("Numbers only!")
except ZeroDivisionError:
print("Total can't be zero!")
try:
human_years = int(input("Dog's age: "))
dog_years = human_years * 7
print(f"Dog age: {dog_years}")
except ValueError:
print("Enter whole number!")
except Exception:
print("Something unexpected happened!")
finallytry:
file = open("diary.txt", "r")
print(file.read())
except FileNotFoundError:
print("Diary not found!")
finally:
file.close() # This always runs
print("File handler cleaned up")
else Clausetry blocktry:
result = 10 / num
except ZeroDivisionError:
print("Can't divide by zero!")
else:
print(f"Result is {result}") # Only if successful
else?try block# Without else
try:
config = open("settings.cfg")
# More code here...
# Could accidentally catch exceptions from this code
# With else
try:
config = open("settings.cfg")
except:
#...
else:
# Safe code here
config_file = False
try:
config_file = open("game_config.cfg")
except FileNotFoundError:
print("⚠ Config file missing!")
else:
settings = config_file.read()
print(" Game configuration loaded!")
finally:
if config_file:
config_file.close()
print("Resource cleanup completed")
try: Attempt risky operationexcept: Handle known errorselse: Process success casefinally: Cleanup resourcesdef safe_divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Division by zero!")
else:
print(f"Result is {result}")
finally:
print("Operation complete")
safe_divide(10, 2)
safe_divide(5, 0)
import requests
try:
response = requests.get("https://www.google.com", timeout=3)
except requests.exceptions.ConnectTimeout:
print("Oops! Connection took too long!")
What happens:
import time,requests
wait_time=3
for attempt in range(3):
try:
requests.get("https://www.google.com",timeout=3)
break
except Exception:
print(f"Attempt {attempt+1} failed")
time.sleep(wait_time)
First time: 3s Second time: 2s Third time: 1s
existing_users = ["alice", "bob", "charlie"]
try:
new_user = input("Choose username: ")
if new_user in existing_users:
raise ValueError("Username taken!")
except ValueError as e:
print(e)
def check_password(pwd):
if len(pwd) < 8:
raise Exception("Password too short!")
if not any(c.isdigit() for c in pwd):
raise Exception("Add numbers!")
try:
check_password("weak")
except Exception as e:
print("Weak password: "+str(e))
try:
fahr = float(input("Enter Fahrenheit: "))
except ValueError:
print("Numbers only please!")
else:
celsius = (fahr - 32) * 5/9
print(f"{fahr}F = {celsius:.1f}C")
try:
temp = float(input("Enter temp (-100 to 212F): "))
if not (-100 <= temp <= 212):
raise ValueError("Unrealistic temperature!")
except ValueError as e:
print(f"Invalid input: {e}")