Master dictionaries, file handling, and exception handling through hands-on coding challenges.
Build robust Python applications with dictionaries, files, and proper error handling.
student = {
"name": "Alice",
"age": 20,
"grade": "A",
"courses": ["Math", "Science", "English"]
}
• Dictionaries use curly braces {}student["name"] → "Alice"student.get("age") → 20 (safer, returns None if key missing)student.get("email", "N/A") → "N/A" (default value)student["email"] = "alice@school.edu" (adds new key)student["age"] = 21 (updates existing key)student.keys() → dict_keys(['name', 'age', ...])student.values() → dict_values(['Alice', 20, ...])student.items() → dict_items([('name', 'Alice'), ...])for key, value in student.items():
print(f"{key}: {value}")if "name" in student:del student["grade"] or student.pop("grade")dict1.update(dict2) or {**dict1, **dict2}{x: x**2 for x in range(5)}Name: Alice
Age: 20
Grade: A
Courses: ['Math', 'Science', 'English']
Email added: alice@school.edu
All keys: dict_keys(['name', 'age', 'grade', 'courses', 'email'])
student = {"name": "Alice", "age": 20}student["name"] or student.get("name")student["email"] = "test@mail.com"student.keys()for key, value in student.items():if "name" in student:Review feedback below
open() with mode "w":file = open("output.txt", "w")
file.write("Hello, World!")
file.close()
• "w" mode creates file or overwrites existing contentwith open("output.txt", "w") as file:
file.write("Line 1\n")
file.write("Line 2\n")
• Automatically closes file when block endswith open("output.txt", "r") as file:
content = file.read() # Read entire file
# OR
lines = file.readlines() # Read as list of lines
# OR
for line in file: # Read line by line
print(line)"r" - Read (default). Error if file doesn't exist"w" - Write. Creates new or overwrites existing"a" - Append. Creates new or adds to existing"x" - Exclusive create. Error if file exists"b" - Binary mode (e.g., "rb", "wb")"+" - Read and write (e.g., "r+", "w+")\n for newlines when writingstrip() removes trailing newlines when readingimport os; os.path.exists("file.txt")csv modulejson moduleFile written successfully!
Reading file content:
Hello, Python!
This is line 2.
This is line 3.
with open("file.txt", "w") as f:with open("file.txt", "r") as f:f.write("Hello\n")content = f.read()lines = f.readlines()Review feedback below
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
• Code that might fail goes in the try blockexcept blocktry:
value = int(input("Enter a number: "))
result = 10 / value
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero!")try:
risky_operation()
except Exception as e:
print(f"An error occurred: {e}")
• Captures the exception object as etry:
result = 10 / 2
except ZeroDivisionError:
print("Error!")
else:
print(f"Success! Result: {result}") # Runs if NO exception
finally:
print("This always runs!") # Cleanup code
• else runs only if try block succeedsfinally ALWAYS runs (cleanup, close files, etc.)ValueError - Wrong value type (e.g., int("abc"))TypeError - Wrong operation for typeKeyError - Dictionary key not foundIndexError - List index out of rangeFileNotFoundError - File doesn't existZeroDivisionError - Division by zeroexcept: (catches everything including KeyboardInterrupt)raise to re-raise or create exceptionsclass MyError(Exception): passTesting division by zero...
Error: Cannot divide by zero!
Testing invalid conversion...
Error: Invalid number format!
Testing successful operation...
Success! Result: 5.0
Cleanup complete.
try: ... except ExceptionType: ...except Exception as e:except (TypeError, ValueError):else: (runs if no exception)finally: (always runs)Review feedback below