Python Programming Labs

Master dictionaries, file handling, and exception handling through hands-on coding challenges.

Data Structures & Error Handling - Module 3

Build robust Python applications with dictionaries, files, and proper error handling.

Lab 7: Dictionaries
Intermediate
Coding Challenge
Your Task: Create and manipulate a Python dictionary to store student information. Dictionaries are one of Python's most powerful and commonly used data structures.

Detailed Requirements:
1. Create a dictionary called "student" with key-value pairs:
student = { "name": "Alice", "age": 20, "grade": "A", "courses": ["Math", "Science", "English"] }    • Dictionaries use curly braces {}
   • Each item is a key:value pair separated by colons
   • Keys must be immutable (strings, numbers, tuples)
   • Values can be any data type, including lists or other dicts

2. Access values using keys:
   • student["name"] → "Alice"
   • student.get("age") → 20 (safer, returns None if key missing)
   • student.get("email", "N/A") → "N/A" (default value)

3. Add or update values:
   • student["email"] = "alice@school.edu" (adds new key)
   • student["age"] = 21 (updates existing key)

4. Get all keys, values, or items:
   • student.keys() → dict_keys(['name', 'age', ...])
   • student.values() → dict_values(['Alice', 20, ...])
   • student.items() → dict_items([('name', 'Alice'), ...])

5. Loop through a dictionary:
for key, value in student.items(): print(f"{key}: {value}")

💡 Pro Tips:
• Check if key exists: if "name" in student:
• Remove a key: del student["grade"] or student.pop("grade")
• Merge dictionaries: dict1.update(dict2) or {**dict1, **dict2}
• Dictionary comprehension: {x: x**2 for x in range(5)}

Expected Output:
Name: Alice Age: 20 Grade: A Courses: ['Math', 'Science', 'English'] Email added: alice@school.edu All keys: dict_keys(['name', 'age', 'grade', 'courses', 'email'])

Requirements Checklist

Create a dictionary called "student" with at least 3 key-value pairs
Access values using bracket notation or .get()
Add a new key-value pair to the dictionary
Use .keys(), .values(), or .items()
Loop through the dictionary with for loop
Print dictionary contents
Output
# Click "Run Code" to execute your Python code # Your program output will appear here
Hints & Tips
• Create dict: student = {"name": "Alice", "age": 20}
• Access value: student["name"] or student.get("name")
• Add/update: student["email"] = "test@mail.com"
• Get keys: student.keys()
• Loop: for key, value in student.items():
• Check key exists: if "name" in student:
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 8: File Handling
Intermediate
Coding Challenge
Your Task: Learn to read from and write to files in Python. File handling is essential for data persistence, logging, and working with external data.

Detailed Requirements:
1. Open a file for writing using open() with mode "w":
file = open("output.txt", "w") file.write("Hello, World!") file.close()    • "w" mode creates file or overwrites existing content
   • "a" mode appends to existing content
   • Always close files when done!

2. Use the "with" statement (context manager - RECOMMENDED):
with open("output.txt", "w") as file: file.write("Line 1\n") file.write("Line 2\n")    • Automatically closes file when block ends
   • Handles exceptions properly
   • Always prefer "with" over manual open/close

3. Read from a file:
with 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)

4. File modes explained:
   • "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+")

💡 Pro Tips:
• Use \n for newlines when writing
strip() removes trailing newlines when reading
• Check if file exists: import os; os.path.exists("file.txt")
• For CSV files, use the csv module
• For JSON files, use the json module

Expected Output:
File written successfully! Reading file content: Hello, Python! This is line 2. This is line 3.

Requirements Checklist

Use open() function with appropriate mode
Use "with" statement for file handling
Write content to a file using .write()
Read content from a file using .read() or .readlines()
Use newline characters (\n) in your output
Print the file contents after reading
Output
# Click "Run Code" to execute your Python code
Hints & Tips
• Write mode: with open("file.txt", "w") as f:
• Read mode: with open("file.txt", "r") as f:
• Write text: f.write("Hello\n")
• Read all: content = f.read()
• Read lines: lines = f.readlines()
• Always use "with" to auto-close files!
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 9: Exception Handling
Intermediate
Coding Challenge
Your Task: Master Python exception handling to write robust code that gracefully handles errors. Proper error handling prevents crashes and provides helpful feedback.

Detailed Requirements:
1. Basic try-except block:
try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!")    • Code that might fail goes in the try block
   • Error handling code goes in except block
   • Program continues after handling the exception

2. Handle multiple exception types:
try: 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!")

3. Catch any exception (use sparingly):
try: risky_operation() except Exception as e: print(f"An error occurred: {e}")    • Captures the exception object as e
   • Good for logging, but be specific when possible

4. Use else and finally:
try: 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 succeeds
   • finally ALWAYS runs (cleanup, close files, etc.)

Common Exception Types:
   • ValueError - Wrong value type (e.g., int("abc"))
   • TypeError - Wrong operation for type
   • KeyError - Dictionary key not found
   • IndexError - List index out of range
   • FileNotFoundError - File doesn't exist
   • ZeroDivisionError - Division by zero

💡 Pro Tips:
• Be specific with exception types when possible
• Don't use bare except: (catches everything including KeyboardInterrupt)
• Use raise to re-raise or create exceptions
• Custom exceptions: class MyError(Exception): pass

Expected Output:
Testing division by zero... Error: Cannot divide by zero! Testing invalid conversion... Error: Invalid number format! Testing successful operation... Success! Result: 5.0 Cleanup complete.

Requirements Checklist

Use try-except block to catch an exception
Handle ZeroDivisionError specifically
Handle ValueError for type conversion errors
Use "except Exception as e" to capture error details
Include a finally block for cleanup
Print appropriate error messages
Output
# Click "Run Code" to execute your Python code
Hints & Tips
• Basic: try: ... except ExceptionType: ...
• Capture error: except Exception as e:
• Multiple: except (TypeError, ValueError):
• Success block: else: (runs if no exception)
• Cleanup: finally: (always runs)
• Be specific with exception types!
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below