Python Programming Labs

Master Object-Oriented Programming and advanced Python concepts through hands-on challenges.

OOP & Advanced Python - Module 4

Level up your Python skills with classes, comprehensions, and functional programming.

Lab 10: Classes & Object-Oriented Programming
Advanced
Coding Challenge
Your Task: Create a Python class to model a real-world object. Classes are blueprints for creating objects with shared attributes and behaviors.

Detailed Requirements:
1. Create a class called "Car" with an __init__ method:
class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer = 0    • class keyword defines a new class (capitalize class names)
   • __init__ is the constructor, called when creating new objects
   • self refers to the current instance (like "this" in other languages)
   • Instance attributes are defined with self.attribute = value

2. Add a method to display car info:
def get_description(self): return f"{self.year} {self.make} {self.model}"    • Methods are functions defined inside a class
   • First parameter is always self

3. Add a method to drive the car:
def drive(self, miles): self.odometer += miles print(f"Drove {miles} miles. Total: {self.odometer}")

4. Create instances and call methods:
my_car = Car("Toyota", "Camry", 2023) print(my_car.get_description()) my_car.drive(100)

💡 Pro Tips:
• Use __str__ method for printable representation
• Class attributes (shared by all instances): define outside __init__
• Private attributes: prefix with underscore _private
• Inheritance: class ElectricCar(Car):
super().__init__() to call parent constructor

Expected Output:
Car created: 2023 Toyota Camry Description: 2023 Toyota Camry Drove 100 miles. Total: 100 Drove 50 miles. Total: 150 Current odometer: 150

Requirements Checklist

Define a class called "Car"
Implement __init__ method with parameters
Use self to create instance attributes
Create at least one additional method
Create an instance of the class
Call methods on the instance
Output
# Click "Run Code" to execute your Python code # Your program output will appear here
Hints & Tips
• Define class: class Car: (capitalize name)
• Constructor: def __init__(self, param1, param2):
• Instance attribute: self.make = make
• Method: def method_name(self):
• Create instance: my_car = Car("Toyota", "Camry", 2023)
• Call method: my_car.get_description()
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 11: List Comprehensions
Advanced
Coding Challenge
Your Task: Master Python list comprehensions - a concise and Pythonic way to create lists. They're more readable and often faster than traditional for loops.

Detailed Requirements:
1. Basic list comprehension - create a list of squares:
# Traditional way: squares = [] for x in range(10): squares.append(x ** 2) # List comprehension (one line!): squares = [x ** 2 for x in range(10)] # Result: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]    • Format: [expression for item in iterable]
   • Expression is applied to each item

2. Add a condition (filter) - even numbers only:
# Only squares of even numbers: even_squares = [x ** 2 for x in range(10) if x % 2 == 0] # Result: [0, 4, 16, 36, 64]    • Format: [expression for item in iterable if condition]

3. Transform strings:
names = ["alice", "bob", "charlie"] upper_names = [name.upper() for name in names] # Result: ["ALICE", "BOB", "CHARLIE"]

4. Nested comprehensions:
# Flatten a 2D list: matrix = [[1, 2], [3, 4], [5, 6]] flat = [num for row in matrix for num in row] # Result: [1, 2, 3, 4, 5, 6]

5. With if-else (conditional expression):
numbers = [1, 2, 3, 4, 5] labels = ["even" if x % 2 == 0 else "odd" for x in numbers] # Result: ["odd", "even", "odd", "even", "odd"]

💡 Pro Tips:
• Dictionary comprehension: {k: v for k, v in items}
• Set comprehension: {x for x in items}
• Generator expression (memory efficient): (x for x in items)
• Don't overuse - if it's hard to read, use a regular loop

Expected Output:
Squares: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] Even squares: [0, 4, 16, 36, 64] Upper names: ['ALICE', 'BOB', 'CHARLIE'] Filtered: [6, 7, 8, 9, 10]

Requirements Checklist

Create a basic list comprehension (e.g., squares)
Use a condition/filter in a list comprehension
Transform strings using list comprehension
Use range() in your comprehension
Print the resulting lists
Create at least 3 different list comprehensions
Output
# Click "Run Code" to execute your Python code
Hints & Tips
• Basic: [expression for item in iterable]
• With filter: [x for x in range(10) if x > 5]
• Transform: [s.upper() for s in strings]
• Squares: [x ** 2 for x in range(10)]
• If-else: ["even" if x%2==0 else "odd" for x in nums]
• Keep it readable - don't make it too complex!
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 12: Lambda & Functional Programming
Advanced
Coding Challenge
Your Task: Master Python lambda functions and functional programming concepts like map(), filter(), and sorted() with custom keys.

Detailed Requirements:
1. Create a lambda function:
# Regular function: def square(x): return x ** 2 # Lambda equivalent (anonymous function): square = lambda x: x ** 2 print(square(5)) # Output: 25    • Syntax: lambda arguments: expression
   • Can have multiple arguments: lambda x, y: x + y
   • Single expression only (no statements)

2. Use map() with lambda - apply function to all items:
numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x ** 2, numbers)) # Result: [1, 4, 9, 16, 25]    • map(function, iterable) applies function to each item
   • Returns an iterator, wrap in list() to see results

3. Use filter() with lambda - keep items matching condition:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] evens = list(filter(lambda x: x % 2 == 0, numbers)) # Result: [2, 4, 6, 8, 10]    • filter(function, iterable) keeps items where function returns True

4. Use sorted() with lambda key:
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)] # Sort by score (second element): by_score = sorted(students, key=lambda x: x[1]) # Result: [("Charlie", 78), ("Alice", 85), ("Bob", 92)] # Sort descending: by_score_desc = sorted(students, key=lambda x: x[1], reverse=True)

5. Use reduce() (from functools) - accumulate values:
from functools import reduce numbers = [1, 2, 3, 4, 5] product = reduce(lambda x, y: x * y, numbers) # Result: 120 (1*2*3*4*5)

💡 Pro Tips:
• Use lambdas for simple, one-time functions
• For complex logic, use regular def functions
• Lambdas are great as arguments to map/filter/sorted
• List comprehensions often replace map() and filter()

Expected Output:
Lambda square: 25 Mapped squares: [1, 4, 9, 16, 25] Filtered evens: [2, 4, 6, 8, 10] Sorted by score: [('Charlie', 78), ('Alice', 85), ('Bob', 92)]

Requirements Checklist

Create a lambda function and call it
Use map() with a lambda function
Use filter() with a lambda function
Use sorted() with a lambda key
Work with a list of tuples or dictionaries
Print results of functional operations
Output
# Click "Run Code" to execute your Python code
Hints & Tips
• Lambda: lambda x: x ** 2
• Multi-arg: lambda x, y: x + y
• Map: list(map(lambda x: x*2, nums))
• Filter: list(filter(lambda x: x>5, nums))
• Sorted: sorted(items, key=lambda x: x[1])
• Remember to wrap map/filter in list()!
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below