Python Programming Lab

Master Python from basics to object-oriented programming

8 Exercises 90-120 minutes All Levels

Learning Objectives

1

Python Basics & Variables

Beginner

Python's simple syntax makes it perfect for learning programming. Let's start with variables and data types.

Concept Overview

Python uses dynamic typing—you don't need to declare variable types. The interpreter figures it out based on the assigned value.

# Variables and data types name = "Hexworth" # str age = 25 # int gpa = 3.85 # float is_enrolled = True # bool # Type checking print(type(name)) # <class 'str'> print(type(age)) # <class 'int'>

Tasks

  • Create variables for: your name, birth year, and whether you like Python
  • Calculate your age from your birth year and store it
  • Use type() to verify each variable's data type
  • Print all variables with descriptive labels
  • Experiment with arithmetic operators (+, -, *, /, //, %, **)
Hint

Use 2025 - birth_year to calculate age. For exponents, 2 ** 3 equals 8.

Related Visualizers

Python Chapter 1: Introduction

Reflection

How does Python's dynamic typing compare to languages you've used before?

2

String Operations & Formatting

Beginner

Strings in Python are immutable sequences of characters with powerful built-in methods.

Concept Overview

# String slicing text = "Hexworth Prime" print(text[0]) # H (first char) print(text[-1]) # e (last char) print(text[0:8]) # Hexworth (slice) print(text[::-1]) # emirP htrowxeH (reversed) # String methods print(text.upper()) # HEXWORTH PRIME print(text.split()) # ['Hexworth', 'Prime'] print(text.replace("Prime", "Academy")) # f-strings (Python 3.6+) name = "Alice" score = 95 print(f"{name} scored {score}%")

Tasks

  • Create a string with your full name and extract first/last name using slicing
  • Check if a substring exists using in operator
  • Count occurrences of a letter using .count()
  • Create a formatted string using f-strings with at least 3 variables
  • Reverse your name string using slicing
Expected Pattern
Full name: John Doe
First name: John
Letter 'o' appears 2 times
Reversed: eoD nhoJ

Related Visualizers

Python Chapter 2: Strings
3

Control Flow: Conditionals & Loops

Beginner

Control flow lets your program make decisions and repeat actions.

Concept Overview

# Conditionals score = 85 if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" else: grade = "F" # For loop with range for i in range(5): print(f"Iteration {i}") # While loop count = 0 while count < 3: print(f"Count: {count}") count += 1 # Loop control for num in range(10): if num == 5: continue # Skip 5 if num == 8: break # Stop at 8 print(num)

Tasks

  • Write a grade calculator that accepts a score and outputs a letter grade
  • Create a FizzBuzz program (print Fizz for multiples of 3, Buzz for 5, FizzBuzz for both)
  • Use a while loop to find the first number divisible by both 7 and 11
  • Create a number guessing game with limited attempts
  • Print a triangle pattern using nested loops (5 rows)
Triangle Pattern Output
*
**
***
****
*****
FizzBuzz Hint

Check for divisibility by 15 first (both 3 and 5), then 3, then 5, then just print the number.

Related Visualizers

Python Chapter 3: Flow Control
4

Functions & Scope

Intermediate

Functions are reusable blocks of code that perform specific tasks. They help organize code and avoid repetition.

Concept Overview

# Basic function def greet(name): """Return a greeting message.""" return f"Hello, {name}!" # Default parameters def power(base, exponent=2): return base ** exponent print(power(3)) # 9 (default exponent) print(power(2, 3)) # 8 # *args and **kwargs def sum_all(*args): return sum(args) def describe(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") # Lambda functions square = lambda x: x ** 2 print(square(5)) # 25

Tasks

  • Create a function that calculates the area of a rectangle with default width=1
  • Write a function that returns both the sum and average of numbers using *args
  • Create a password validator function that checks length and character requirements
  • Write a recursive function to calculate factorial
  • Use lambda with sorted() to sort a list of tuples by second element
# Example for task 5 students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)] # Sort by score (second element) descending sorted_students = sorted(students, key=lambda x: x[1], reverse=True)

Related Visualizers

Python Chapter 4: Functions

Reflection

When would you choose a lambda function over a regular function?

5

Collections: Lists & Tuples

Intermediate

Lists are mutable ordered collections; tuples are immutable. Both are fundamental Python data structures.

Concept Overview

# Lists (mutable) fruits = ["apple", "banana", "cherry"] fruits.append("date") # Add to end fruits.insert(1, "avocado") # Insert at index fruits.remove("banana") # Remove by value popped = fruits.pop() # Remove and return last # List comprehensions squares = [x**2 for x in range(10)] evens = [x for x in range(20) if x % 2 == 0] # Tuples (immutable) coordinates = (10, 20) x, y = coordinates # Unpacking # Common list operations numbers = [3, 1, 4, 1, 5, 9] print(sum(numbers)) # 23 print(min(numbers)) # 1 print(max(numbers)) # 9 print(sorted(numbers)) # [1, 1, 3, 4, 5, 9]

Tasks

  • Create a list of 10 random numbers and find sum, average, min, max
  • Use list comprehension to filter even numbers and square them
  • Create a matrix (list of lists) and access specific elements
  • Write a function that removes duplicates from a list while preserving order
  • Use tuple unpacking to swap two variables without a temp variable
# Matrix example matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(matrix[1][2]) # 6 (row 1, col 2)

Related Visualizers

Python Chapter 5: Collections
6

Dictionaries & Sets

Intermediate

Dictionaries store key-value pairs with O(1) lookup. Sets store unique unordered elements.

Concept Overview

# Dictionaries student = { "name": "Alice", "age": 20, "courses": ["Python", "Security"] } # Accessing values print(student["name"]) # Alice print(student.get("gpa", 0)) # 0 (default if not found) # Dictionary methods print(student.keys()) # dict_keys(['name', 'age', 'courses']) print(student.values()) # dict_values([...]) print(student.items()) # dict_items([(...)]) # Dictionary comprehension squares = {x: x**2 for x in range(5)} # Sets unique = {1, 2, 3, 2, 1} # {1, 2, 3} a = {1, 2, 3} b = {2, 3, 4} print(a | b) # Union: {1, 2, 3, 4} print(a & b) # Intersection: {2, 3}

Tasks

  • Create a dictionary for a product catalog with nested information
  • Write a function that counts character frequency in a string
  • Merge two dictionaries and handle key conflicts
  • Use sets to find common elements between two lists
  • Create a phone book program (add, search, delete contacts)
Operation Dictionary Set
Create {key: value} {element}
Add d[key] = value s.add(elem)
Remove del d[key] s.remove(elem)
Check key in d elem in s

Related Visualizers

Python Chapter 6: Dictionaries
7

File Handling & Exceptions

Intermediate

Python makes file operations simple with built-in functions and context managers.

Concept Overview

# Writing to a file with open("data.txt", "w") as f: f.write("Hello, World!\n") f.write("Line 2") # Reading from a file with open("data.txt", "r") as f: content = f.read() # Entire file # OR lines = f.readlines() # List of lines # OR for line in f: # Line by line (memory efficient) print(line.strip()) # Exception handling try: with open("missing.txt") as f: data = f.read() except FileNotFoundError: print("File not found!") except PermissionError: print("No permission!") finally: print("Cleanup here")

Tasks

  • Write a program that saves user input to a file
  • Read a CSV-like file and parse it into a list of dictionaries
  • Implement proper exception handling for all file operations
  • Create a simple log file system that appends timestamps
  • Write a word counter that processes a text file
# File mode reference # 'r' - Read (default) # 'w' - Write (overwrites) # 'a' - Append # 'x' - Exclusive create (fails if exists) # 'b' - Binary mode (e.g., 'rb', 'wb') # '+' - Read and write (e.g., 'r+')
CSV Parsing Hint

Use line.strip().split(',') to split CSV lines. The first line usually contains headers.

Related Visualizers

Python Chapter 7: File Handling
8

Object-Oriented Programming

Advanced

OOP organizes code into reusable, modular classes that model real-world entities.

Concept Overview

class BankAccount: """A simple bank account class.""" # Class variable (shared by all instances) interest_rate = 0.02 def __init__(self, owner, balance=0): # Instance variables self.owner = owner self._balance = balance # Convention: "protected" def deposit(self, amount): if amount > 0: self._balance += amount return True return False def withdraw(self, amount): if 0 < amount <= self._balance: self._balance -= amount return amount return None @property def balance(self): return self._balance def __str__(self): return f"Account({self.owner}: ${self._balance})" # Inheritance class SavingsAccount(BankAccount): def __init__(self, owner, balance=0): super().__init__(owner, balance) self.min_balance = 100 def withdraw(self, amount): if self._balance - amount >= self.min_balance: return super().withdraw(amount) return None

Tasks

  • Create a Student class with name, ID, and grade tracking
  • Implement a Course class that can enroll multiple students
  • Use inheritance to create GraduateStudent from Student
  • Add a class method and a static method to your class
  • Implement __str__ and __repr__ for useful output
# OOP Pillars to implement: # 1. Encapsulation - Use private/protected attributes # 2. Inheritance - Child classes extend parent # 3. Polymorphism - Same interface, different behavior # 4. Abstraction - Hide complexity behind simple interface

Related Visualizers

Python Chapter 8: OOP

Final Reflection

Design a class hierarchy for a library management system. What classes would you need? What would inherit from what?