๐Ÿ Python in 12 Days

Beginner to Intermediate โ€” A Self-Paced, Printable Course

Daily lessons ยท Hands-on tasks ยท Paper worksheets ยท Test sheets with answer key

Course Roadmap

  1. Day 1 โ€” Python Basics: print, variables, data types
  2. Day 2 โ€” Operators, Type Casting, Input
  3. Day 3 โ€” Strings & String Methods (+ Test 1)
  4. Day 4 โ€” Lists
  5. Day 5 โ€” Tuples & Sets
  6. Day 6 โ€” Dictionaries (+ Test 2)
  7. Day 7 โ€” Conditional Statements
  8. Day 8 โ€” Loops (for, while)
  9. Day 9 โ€” Functions (+ Test 3)
  10. Day 10 โ€” Modules & File Handling
  11. Day 11 โ€” Exception Handling & Intro to OOP
  12. Day 12 โ€” OOP: Inheritance + Mini Project (+ Final Test)

How to use this: Each day has 3 parts โ€” Learn (read the explanations and examples), Do (a coding task on your computer), and Worksheet (paper-based practice, no computer). Test sheets appear every 3 days. Answers to every worksheet and test are in the Answer Key at the very end โ€” don't peek early!

Day 1 โ€” Python Basics

Beginner
โฑ Learn: 40 min๐Ÿ’ป Task: 30 min๐Ÿ“ Worksheet: 20 min

1. What is Python?

Python is a high-level, interpreted programming language known for its readable syntax. It's used in web development, data science, automation, AI, and pharma-tech tools alike. Unlike C or Java, Python doesn't need you to declare variable types explicitly, and it runs line by line (interpreted), which makes it great for beginners.

2. Your First Program: print()

The print() function displays output on the screen. It's usually the very first thing anyone learns.

print("Hello, World!")
print("Ananya is learning Python")
print(2 + 3)          # prints 5
๐Ÿ’ก Anything inside quotes " " or ' ' is treated as text (a string), not code.

3. Variables

A variable is a named container that stores a value. You don't need to declare its type โ€” Python figures it out automatically.

name = "Ananya"
age = 20
height = 5.4
is_founder = True

print(name, age, height, is_founder)
๐Ÿ“ Naming rules: variable names can contain letters, digits, and underscores, but can't start with a digit. my_var โœ…   2var โŒ

4. Data Types

TypeExampleMeaning
int10Whole number
float3.14Decimal number
str"hello"Text
boolTrue / FalseLogical value

Use type() to check any variable's data type:

print(type(10))        # <class 'int'>
print(type("hi"))       # <class 'str'>

5. Comments

Comments are notes for humans; Python ignores them. Use # for a single line.

# This is a comment โ€” Python will not run this line
print("This line runs")  # you can also comment after code

๐Ÿ’ป Today's Task (30 min)

Open a Python environment (IDLE, VS Code, or an online compiler like replit.com). Write a script that:

  1. Prints your name, age, and one hobby using separate variables.
  2. Prints the type() of each of those three variables.
  3. Adds a comment above each print statement explaining what it does.

๐Ÿ“ Day 1 Worksheet (paper, no computer)

1. What will type(7.0) return?
2. Fix the invalid variable name: 1st_place = "gold"
3. Write a line of code that prints My name is Ananya using a variable called name.
4. What is the output of: print("5" + "5")? Explain why.
5. True or False: Python requires you to declare a variable's type before using it.

Day 2 โ€” Operators, Type Casting & Input

Beginner
โฑ Learn: 40 min๐Ÿ’ป Task: 30 min๐Ÿ“ Worksheet: 20 min

1. Arithmetic Operators

print(7 + 2)   # 9   addition
print(7 - 2)   # 5   subtraction
print(7 * 2)   # 14  multiplication
print(7 / 2)   # 3.5 division (always returns float)
print(7 // 2)  # 3   floor division (drops decimal)
print(7 % 2)   # 1   modulus (remainder)
print(7 ** 2)  # 49  exponent (power)

2. Comparison & Logical Operators

print(5 > 3)      # True
print(5 == 5)     # True (equality check)
print(5 != 4)     # True (not equal)

a = True
b = False
print(a and b)    # False โ€” both must be True
print(a or b)     # True  โ€” at least one True
print(not a)      # False โ€” flips the value

3. Type Casting

Converting one data type into another using int(), float(), str(), bool().

x = "10"
y = int(x)          # "10" -> 10
print(y + 5)          # 15

z = str(25)          # 25 -> "25"
print("Score: " + z)
โš ๏ธ int("hello") will crash your program with a ValueError โ€” only convert text that actually looks like a number.

4. Taking Input from the User

input() always returns a string, even if the user types a number โ€” you must cast it yourself.

name = input("What is your name? ")
age = int(input("What is your age? "))

print(name + " is " + str(age) + " years old")

๐Ÿ’ป Today's Task (30 min)

Write a small "BMI-style" calculator:

  1. Ask the user for their weight (kg) and height (m) using input().
  2. Cast both to float.
  3. Calculate: bmi = weight / (height ** 2)
  4. Print the result rounded using round(bmi, 2).

๐Ÿ“ Day 2 Worksheet

1. What does 17 // 5 evaluate to?
2. What does 17 % 5 evaluate to?
3. Convert the string "3.9" into a float and add 0.1 to it. Write the code.
4. What type does input() always return, regardless of what the user types?
5. Evaluate: (4 > 2) and (3 == 4)

Day 3 โ€” Strings & String Methods

Beginner
โฑ Learn: 45 min๐Ÿ’ป Task: 30 min๐Ÿ“ Worksheet: 20 min

1. Strings & Indexing

A string is a sequence of characters. Each character has a position (index), starting at 0.

word = "Python"
print(word[0])     # 'P'
print(word[-1])    # 'n' (last character)
print(word[0:3])   # 'Pyt' (slicing: start to end-1)
print(len(word))   # 6

2. Common String Methods

s = "  Hello Ananya  "
print(s.strip())          # removes leading/trailing spaces
print(s.lower())          # "  hello ananya  "
print(s.upper())          # "  HELLO ANANYA  "
print(s.replace("Hello", "Hey"))
print(s.strip().split(" "))   # ['Hello', 'Ananya']
print("-".join(["a","b","c"]))  # "a-b-c"
print("Python" in "I love Python")   # True

3. String Formatting (f-strings)

The modern, cleanest way to insert variables into text:

name = "Ananya"
project = "Viginyx"
print(f"{name} is building {project}")

score = 91.567
print(f"Score: {score:.2f}")   # Score: 91.57 (2 decimal places)

๐Ÿ’ป Today's Task (30 min)

Write a program that takes a sentence as input and:

  1. Prints how many words it has (hint: .split())
  2. Prints the sentence in all uppercase
  3. Prints the sentence reversed (hint: text[::-1])
  4. Uses an f-string to print: "Your sentence had X words."

๐Ÿ“ Day 3 Worksheet

1. Given s = "Pharmacy", what is s[2:5]?
2. Write code to convert "HELLO" to lowercase.
3. What does "cat" in "concatenate" return?
4. Write an f-string that prints: Name: Ananya, Age: 20 using variables n and a.
5. What does len("VCMC") return?

๐Ÿงช Test 1 โ€” Days 1 to 3

Basics, Operators, Strings โ€” 30 minutes, closed book

Score: ____ / 20   Time taken: ______
1. (2 pts) What is the output of print(type(3 / 1))?
2. (2 pts) What is the difference between / and //?
3. (2 pts) Write a variable assignment for a boolean called is_active set to True.
4. (2 pts) Evaluate: 10 % 3 + 2 ** 2
5. (3 pts) Given x = "42", write code to convert it to an integer and print x + 8 correctly.
6. (3 pts) Given s = "Molecular Cipher", write the code to print only "Molecular" using slicing.
7. (3 pts) What does "abc".upper().replace("A", "X") return?
8. (3 pts) Write an f-string that prints "Total: 45.00" from a variable total = 45, formatted to 2 decimal places.

Day 4 โ€” Lists

Beginner โ†’ Intermediate
โฑ Learn: 45 min๐Ÿ’ป Task: 30 min๐Ÿ“ Worksheet: 20 min

1. What is a List?

A list is an ordered, changeable (mutable) collection that can hold mixed data types.

fruits = ["apple", "banana", "cherry"]
mixed = [1, "two", 3.0, True]

print(fruits[0])     # apple
print(fruits[-1])    # cherry
print(len(fruits))   # 3

2. Modifying Lists

fruits.append("mango")        # add to end
fruits.insert(1, "kiwi")       # insert at index 1
fruits.remove("banana")        # remove by value
fruits.pop()                   # removes last item
fruits[0] = "strawberry"       # update by index

print(fruits)

3. Looping Through a List

for fruit in fruits:
    print(fruit)

# with index
for i, fruit in enumerate(fruits):
    print(i, fruit)

4. List Slicing & Useful Functions

nums = [5, 2, 9, 1, 7]
print(nums[1:4])     # [2, 9, 1]
print(sorted(nums))   # [1, 2, 5, 7, 9]
print(max(nums), min(nums), sum(nums))
nums.sort()            # sorts in place
nums.reverse()          # reverses in place

5. List Comprehension (Intermediate)

A compact way to build lists in one line:

squares = [x**2 for x in range(1, 6)]
print(squares)   # [1, 4, 9, 16, 25]

evens = [x for x in range(10) if x % 2 == 0]
print(evens)     # [0, 2, 4, 6, 8]

๐Ÿ’ป Today's Task (30 min)

Create a list of 5 subjects/skills you're learning. Then:

  1. Add one more using .append()
  2. Sort the list alphabetically
  3. Print each item with its position using enumerate()
  4. Use list comprehension to create a new list with only items that have more than 5 letters

๐Ÿ“ Day 4 Worksheet

1. Given nums = [3, 1, 4, 1, 5], what does nums[1:3] return?
2. What's the difference between .remove() and .pop()?
3. Write a list comprehension that squares every number from 1 to 5.
4. What does sorted([4,2,8,1], reverse=True) return?
5. Write a for loop that prints every item in colors = ["red","blue","green"] along with its index.

Day 5 โ€” Tuples & Sets

Intermediate
โฑ Learn: 35 min๐Ÿ’ป Task: 25 min๐Ÿ“ Worksheet: 20 min

1. Tuples โ€” Ordered & Immutable

A tuple is like a list, but once created, it cannot be changed. Use tuples for fixed data (coordinates, RGB values, constants).

point = (4, 5)
receptor_coords = (127.0, 124.5, 138.0)

print(point[0])       # 4
# point[0] = 10        # โŒ Error! Tuples are immutable

x, y, z = receptor_coords     # unpacking
print(x, y, z)

2. Why Use a Tuple Instead of a List?

3. Sets โ€” Unordered & Unique

A set automatically removes duplicates and has no fixed order.

letters = {"a", "b", "a", "c"}
print(letters)          # {'a', 'b', 'c'} โ€” duplicate removed

a = {1, 2, 3}
b = {2, 3, 4}
print(a.union(b))        # {1,2,3,4}
print(a.intersection(b))  # {2,3}
print(a.difference(b))    # {1}

a.add(5)
a.discard(1)

4. Quick Comparison

TypeOrdered?Mutable?Duplicates?
ListYesYesAllowed
TupleYesNoAllowed
SetNoYesNot allowed

๐Ÿ’ป Today's Task (25 min)

Create two sets of ingredients for two "recipes" (5 items each, with at least 2 overlapping). Print:

  1. Ingredients common to both (intersection)
  2. Ingredients unique to recipe 1 (difference)
  3. All ingredients combined, no duplicates (union)
  4. Then create a tuple storing a fixed "recipe ID" of 3 numbers and unpack it into 3 variables.

๐Ÿ“ Day 5 Worksheet

1. Why would you choose a tuple over a list for GPS coordinates?
2. Given s = {1, 2, 2, 3, 3, 3}, what does print(s) output?
3. Given a = {1,2,3} and b = {3,4,5}, write the result of a.intersection(b).
4. Can you access a set by index like my_set[0]? Why or why not?
5. Write code to unpack coords = (10, 20, 30) into variables x, y, z.

Day 6 โ€” Dictionaries

Intermediate
โฑ Learn: 40 min๐Ÿ’ป Task: 30 min๐Ÿ“ Worksheet: 20 min

1. What is a Dictionary?

A dictionary stores data as key : value pairs. Instead of accessing by index, you access by key.

student = {
    "name": "Ananya",
    "course": "B.Pharm",
    "year": 3
}

print(student["name"])        # Ananya
print(student.get("year"))     # 3
print(student.get("gpa", "N/A"))  # N/A (default if key missing)

2. Modifying a Dictionary

student["year"] = 4              # update
student["college"] = "SVBCP"       # add new key
del student["course"]              # remove a key
print(student.keys())              # all keys
print(student.values())            # all values
print(student.items())             # key-value pairs

3. Looping Through a Dictionary

for key, value in student.items():
    print(f"{key}: {value}")

4. Nested Dictionaries (Intermediate)

Dictionaries can contain other dictionaries or lists โ€” very useful for real-world structured data.

drug_db = {
    "paracetamol": {"dose_mg": 500, "category": "analgesic"},
    "amoxicillin": {"dose_mg": 250, "category": "antibiotic"}
}

print(drug_db["amoxicillin"]["dose_mg"])   # 250

for drug, info in drug_db.items():
    print(f"{drug} -> {info['category']}")

๐Ÿ’ป Today's Task (30 min)

Build a mini "contact book":

  1. Create a dictionary of 3 contacts, where each key is a name and value is a nested dictionary with "phone" and "city".
  2. Loop through and print each contact's details in a readable sentence.
  3. Ask the user for a name using input() and use .get() to safely look them up (print "Not found" if missing).

๐Ÿ“ Day 6 Worksheet

1. What is the key difference between a list and a dictionary?
2. Given d = {"a": 1, "b": 2}, write code to safely get the value of key "c" with a default of 0.
3. Write code to add a new key "gpa": 8.5 to a dictionary called student.
4. What does d.items() return?
5. Write a for loop to print all keys and values of d = {"x": 10, "y": 20}.

๐Ÿงช Test 2 โ€” Days 4 to 6

Lists, Tuples, Sets, Dictionaries โ€” 35 minutes, closed book

Score: ____ / 25   Time taken: ______
1. (3 pts) Given lst = [10, 20, 30, 40], write code to print the list in reverse order without using .reverse().
2. (3 pts) Write a list comprehension that returns only even numbers from range(1, 20).
3. (3 pts) Why can't you do my_tuple[0] = 5?
4. (3 pts) Given a = {1,2,3,4} and b = {3,4,5,6}, write the union and the difference (a - b).
5. (4 pts) Write a dictionary called book with keys "title", "author", "year". Then print a sentence using all three values in one f-string.
6. (4 pts) Given data = {"a": [1,2,3], "b": [4,5,6]}, write code to print the second item of the list stored under key "b".
7. (5 pts) You have a list of exam scores: [45, 88, 67, 92, 34, 76]. Write code to print only the scores above 60, using a list comprehension.

Day 7 โ€” Conditional Statements

Intermediate
โฑ Learn: 35 min๐Ÿ’ป Task: 30 min๐Ÿ“ Worksheet: 20 min

1. if, elif, else

marks = 78

if marks >= 90:
    print("Grade A")
elif marks >= 75:
    print("Grade B")
elif marks >= 50:
    print("Grade C")
else:
    print("Fail")
๐Ÿ’ก Python uses indentation (spaces) instead of curly braces {} to define code blocks. This is not optional โ€” incorrect indentation causes errors.

2. Nested Conditions

age = 20
has_id = True

if age >= 18:
    if has_id:
        print("Entry allowed")
    else:
        print("ID required")
else:
    print("Underage")

3. Combining Conditions

temp = 30
humidity = 80

if temp > 25 and humidity > 70:
    print("Hot and humid")
elif temp > 25 or humidity > 70:
    print("Hot or humid, not both")
else:
    print("Mild weather")

4. Ternary (One-Line) Conditional

age = 17
status = "Adult" if age >= 18 else "Minor"
print(status)

๐Ÿ’ป Today's Task (30 min)

Write a simple grading system:

  1. Ask the user to enter marks (0-100) using input()
  2. Use if/elif/else to print a grade (A/B/C/D/Fail)
  3. Add a check: if the entered number is less than 0 or greater than 100, print "Invalid marks" instead

๐Ÿ“ Day 7 Worksheet

1. What happens if you mix tabs and spaces for indentation in Python?
2. Rewrite using a ternary expression: if x > 0: sign = "positive" else: sign = "non-positive"
3. Trace through: x = 15; what prints? if x > 20: print("big") elif x > 10: print("medium") else: print("small")
4. Write an if statement that checks if a number is divisible by both 3 and 5.
5. What is the output of print("yes" if 5 == 5.0 else "no")?

Day 8 โ€” Loops (for, while)

Intermediate
โฑ Learn: 40 min๐Ÿ’ป Task: 30 min๐Ÿ“ Worksheet: 20 min

1. for Loops

for i in range(5):        # 0,1,2,3,4
    print(i)

for i in range(2, 10, 2):  # start, stop, step -> 2,4,6,8
    print(i)

2. while Loops

Runs as long as a condition is True. You must update the condition inside the loop, or it runs forever.

count = 0
while count < 5:
    print(count)
    count += 1     # same as count = count + 1

3. break and continue

for i in range(10):
    if i == 5:
        break        # exits the loop entirely
    print(i)

for i in range(10):
    if i % 2 == 0:
        continue     # skips this iteration, goes to next
    print(i)          # only prints odd numbers

4. Nested Loops

for i in range(3):
    for j in range(3):
        print(f"i={i}, j={j}")
๐Ÿ’ก Nested loops are common when working with grids, tables, or 2D data โ€” but watch performance for large ranges.

๐Ÿ’ป Today's Task (30 min)

Write a program that:

  1. Prints all multiples of 7 between 1 and 100 using a for loop
  2. Uses a while loop to keep asking the user for a password until they type "python123" correctly
  3. Uses break to stop a loop early when a target number is found in a list

๐Ÿ“ Day 8 Worksheet

1. What does range(3, 15, 3) generate?
2. What's the danger of writing a while loop without updating its condition variable?
3. Trace through and write the output: for i in range(5): if i==3: continue; print(i)
4. Write a loop that prints numbers 10 down to 1 (countdown).
5. What is the difference between break and continue?

Day 9 โ€” Functions

Intermediate
โฑ Learn: 45 min๐Ÿ’ป Task: 30 min๐Ÿ“ Worksheet: 20 min

1. Defining and Calling a Function

def greet(name):
    print(f"Hello, {name}!")

greet("Ananya")     # calling the function

2. Return Values

def add(a, b):
    return a + b

result = add(3, 4)
print(result)         # 7
๐Ÿ’ก print() just displays something; return sends a value back so it can be stored or reused elsewhere.

3. Default Parameters

def power(base, exponent=2):
    return base ** exponent

print(power(5))        # 25 (uses default exponent)
print(power(5, 3))      # 125

4. *args and **kwargs (Intermediate)

Used when you don't know how many arguments will be passed.

def total(*numbers):          # collects extra positional args into a tuple
    return sum(numbers)

print(total(1,2,3,4))          # 10

def profile(**info):            # collects extra keyword args into a dict
    for key, value in info.items():
        print(f"{key}: {value}")

profile(name="Ananya", course="B.Pharm")

5. Lambda Functions

A small, anonymous, one-line function โ€” useful for quick operations.

square = lambda x: x ** 2
print(square(5))          # 25

nums = [1, -2, 3, -4]
print(sorted(nums, key=lambda x: abs(x)))   # sort by absolute value

๐Ÿ’ป Today's Task (30 min)

Write these functions:

  1. is_prime(n) โ€” returns True/False if n is a prime number
  2. average(*nums) โ€” accepts any number of arguments and returns their average
  3. A lambda that converts Celsius to Fahrenheit, applied using map() on a list of temperatures

๐Ÿ“ Day 9 Worksheet

1. What's the difference between print() and return inside a function?
2. Write a function square(n) that returns n squared.
3. What does *args allow a function to do?
4. Convert this to a lambda: def cube(x): return x ** 3
5. Write a function with a default parameter tax_rate=0.18 that calculates final price from a base price.

๐Ÿงช Test 3 โ€” Days 7 to 9

Conditionals, Loops, Functions โ€” 35 minutes, closed book

Score: ____ / 25   Time taken: ______
1. (3 pts) Write an if/elif/else that categorizes a number as "positive", "negative", or "zero".
2. (3 pts) Trace this loop and write its full output: for i in range(1,6): if i%2==0: continue; print(i)
3. (3 pts) Write a while loop that prints "Processing..." 3 times, then prints "Done".
4. (4 pts) Write a function is_even(n) that returns True if n is even, False otherwise.
5. (4 pts) Write a function find_max(numbers) that returns the largest number in a list, without using max().
6. (4 pts) What's the output of: def f(x, y=10): return x + y then print(f(5)) and print(f(5, 20))?
7. (4 pts) Write a lambda that checks whether a number is greater than 100, then use it inside filter() on the list [50, 150, 99, 200].

Day 10 โ€” Modules & File Handling

Intermediate
โฑ Learn: 40 min๐Ÿ’ป Task: 30 min๐Ÿ“ Worksheet: 15 min

1. Importing Modules

import math
print(math.sqrt(16))     # 4.0
print(math.pi)             # 3.14159...

import random
print(random.randint(1, 10))   # random number between 1-10

from datetime import datetime
print(datetime.now())

2. Writing Your Own Module

Any .py file can be imported into another. If you have helper.py with a function def add(a,b): return a+b, you can use it elsewhere with import helper then helper.add(2,3).

3. Reading & Writing Files

# Writing to a file
with open("notes.txt", "w") as f:
    f.write("Hello from Python\n")
    f.write("Second line")

# Reading a file
with open("notes.txt", "r") as f:
    content = f.read()
    print(content)

# Reading line by line
with open("notes.txt", "r") as f:
    for line in f:
        print(line.strip())
๐Ÿ’ก with open(...) as f: automatically closes the file when done โ€” always prefer this over manually calling f.close().

4. File Modes

ModeMeaning
"r"Read (file must exist)
"w"Write (overwrites existing content)
"a"Append (adds to end)

๐Ÿ’ป Today's Task (30 min)

Write a program that:

  1. Uses the random module to generate 5 random numbers between 1-100
  2. Writes those numbers to a file called numbers.txt, one per line
  3. Reads the file back and prints the sum of all numbers

๐Ÿ“ Day 10 Worksheet

1. What's the difference between "w" and "a" file modes?
2. Why is with open(...) as f: preferred over manually opening/closing a file?
3. What does import random followed by random.choice([1,2,3]) do?
4. Write code to write the text "Test" into a file named log.txt.
5. What Python module would you use to work with dates and times?

Day 11 โ€” Exception Handling & Intro to OOP

Intermediate
โฑ Learn: 45 min๐Ÿ’ป Task: 30 min๐Ÿ“ Worksheet: 15 min

1. try / except

Prevents your program from crashing when an error occurs, letting you handle it gracefully.

try:
    num = int(input("Enter a number: "))
    print(10 / num)
except ValueError:
    print("That's not a valid number!")
except ZeroDivisionError:
    print("Can't divide by zero!")
finally:
    print("This always runs, error or not.")

2. Raising Your Own Errors

def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    return age

try:
    set_age(-5)
except ValueError as e:
    print(f"Error: {e}")

3. Object-Oriented Programming: Classes & Objects

A class is a blueprint; an object is an instance built from that blueprint. OOP helps you model real-world things.

class Student:
    def __init__(self, name, course):     # constructor โ€” runs when object is created
        self.name = name
        self.course = course

    def introduce(self):                    # a method
        print(f"Hi, I'm {self.name}, studying {self.course}")

s1 = Student("Ananya", "B.Pharm")
s1.introduce()          # Hi, I'm Ananya, studying B.Pharm
print(s1.name)            # Ananya
๐Ÿ’ก self refers to the specific object calling the method โ€” it's how the object accesses its own data.

๐Ÿ’ป Today's Task (30 min)

Create a class BankAccount with:

  1. __init__(self, owner, balance=0)
  2. A method deposit(amount) that adds to balance
  3. A method withdraw(amount) that raises a ValueError if amount > balance
  4. Wrap a withdrawal attempt in try/except to handle the error gracefully

๐Ÿ“ Day 11 Worksheet

1. What is the purpose of the finally block?
2. What does self represent inside a class method?
3. Write a try/except block that catches a ZeroDivisionError when dividing 10 by a user-input number.
4. What is the difference between a class and an object?
5. Write a class Book with attributes title and author set in __init__.

Day 12 โ€” OOP: Inheritance & Mini Project

Intermediate
โฑ Learn: 35 min๐Ÿ’ป Task: 45 min๐Ÿ“ Worksheet: 15 min

1. Inheritance

A class can inherit attributes and methods from another class โ€” avoiding repeated code.

class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print(f"Hi, I'm {self.name}")

class Student(Person):                 # Student inherits from Person
    def __init__(self, name, course):
        super().__init__(name)          # calls Person's __init__
        self.course = course

    def greet(self):                      # overrides the parent's method
        print(f"Hi, I'm {self.name}, studying {self.course}")

p = Person("Vaibhav")
s = Student("Ananya", "B.Pharm")
p.greet()     # Hi, I'm Vaibhav
s.greet()     # Hi, I'm Ananya, studying B.Pharm

2. Why Inheritance Matters

3. Recap: The Full Toolbox

Over 12 days you've covered: variables & types, operators, strings, lists/tuples/sets/dicts, conditionals, loops, functions (incl. *args/lambda), modules & files, exceptions, and classes/inheritance. That's the core of beginner-to-intermediate Python โ€” everything after this is building bigger projects with these same building blocks.

๐Ÿ’ป Final Mini Project (45 min)

Build a "Contact Manager" console app that combines everything:

  1. Create a class Contact with name, phone, email
  2. Store contacts in a list of Contact objects
  3. Write functions to: add a contact, search by name (using a loop + if), and save all contacts to a file (one per line)
  4. Wrap user input handling in try/except so invalid input doesn't crash the program
  5. Use a while loop with a menu (Add / Search / Save / Exit) that keeps running until the user chooses Exit

๐Ÿ“ Day 12 Worksheet

1. What does super().__init__() do?
2. Write a class Animal with a method speak() that prints "Some sound", then a class Dog(Animal) that overrides speak() to print "Woof".
3. True or False: A child class can only inherit from exactly one parent class in Python.
4. Why is method overriding useful?

๐Ÿ Final Test โ€” Days 10 to 12 (+ Cumulative)

Modules, Files, Exceptions, OOP โ€” 45 minutes, closed book

Score: ____ / 30   Time taken: ______
1. (3 pts) Write code to open a file "data.txt" in append mode and write "New entry" to it.
2. (3 pts) What exception is raised when you try to convert the string "abc" into an integer?
3. (4 pts) Write a try/except/finally block for a function that divides two numbers taken from user input.
4. (4 pts) Write a class Shape with an __init__ that stores a name, and a method describe() that prints it.
5. (4 pts) Write a class Circle(Shape) that inherits from Shape above, adds a radius, and overrides describe() to also print the area (use math.pi).
6. (4 pts) Cumulative: Write a function that takes a list of numbers and returns a new list containing only the even numbers, using list comprehension.
7. (4 pts) Cumulative: Write a dictionary comprehension that maps numbers 1-5 to their cubes. (Hint: {x: x**3 for x in range(1,6)} is the answer style โ€” write your own from scratch first!)
8. (4 pts) Cumulative: Explain in 2-3 sentences the difference between a list, a tuple, and a dictionary โ€” when would you use each?

๐Ÿ“˜ Answer Key

Check your worksheets and tests here. For open-ended "write a function/class" questions, compare structure and logic, not exact wording โ€” many correct versions exist.

Day 1 Worksheet

  1. <class 'float'>
  2. first_place = "gold" (or any name not starting with a digit)
  3. name = "Ananya"; print("My name is " + name)
  4. "55" โ€” with strings, + joins (concatenates) them rather than adding numbers
  5. False โ€” Python infers types automatically

Day 2 Worksheet

  1. 3
  2. 2
  3. float("3.9") + 0.1
  4. str (string), always
  5. False (True and False โ†’ False)

Day 3 Worksheet

  1. "arm"
  2. "HELLO".lower()
  3. True
  4. f"Name: {n}, Age: {a}"
  5. 4

Test 1

  1. <class 'float'>
  2. / gives a precise (float) result; // gives the floored (rounded-down whole) result
  3. is_active = True
  4. 10 % 3 = 1, 2**2 = 4, total = 5
  5. x = "42"; print(int(x) + 8) โ†’ 50
  6. print(s[0:9])
  7. "XBC"
  8. total = 45; print(f"Total: {total:.2f}")

Day 4 Worksheet

  1. [1, 4]
  2. .remove() deletes by value; .pop() deletes by index (default: last item) and returns it
  3. [x**2 for x in range(1,6)]
  4. [8, 4, 2, 1]
  5. for i, c in enumerate(colors): print(i, c)

Day 5 Worksheet

  1. Coordinates shouldn't change accidentally โ€” tuples protect fixed data
  2. {1, 2, 3}
  3. {3}
  4. No โ€” sets are unordered and have no index positions
  5. x, y, z = coords

Day 6 Worksheet

  1. Lists use numeric index positions; dictionaries use named keys
  2. d.get("c", 0)
  3. student["gpa"] = 8.5
  4. All key-value pairs, as tuples, e.g. dict_items([('a',1),('b',2)])
  5. for k, v in d.items(): print(k, v)

Test 2

  1. print(lst[::-1])
  2. [x for x in range(1,20) if x % 2 == 0]
  3. Tuples are immutable โ€” items can't be reassigned after creation
  4. Union: {1,2,3,4,5,6}; Difference (a-b): {1,2}
  5. book = {"title": "...", "author": "...", "year": 2024}; print(f"{book['title']} by {book['author']} ({book['year']})")
  6. print(data["b"][1])
  7. [s for s in [45,88,67,92,34,76] if s > 60]

Day 7 Worksheet

  1. Python raises an IndentationError / TabError โ€” stay consistent (spaces recommended)
  2. sign = "positive" if x > 0 else "non-positive"
  3. "medium" (15 is not > 20, but is > 10)
  4. if n % 3 == 0 and n % 5 == 0:
  5. "yes" โ€” Python treats 5 == 5.0 as True

Day 8 Worksheet

  1. 3, 6, 9, 12
  2. It creates an infinite loop that never stops
  3. 0, 1, 2, 4 (3 is skipped)
  4. for i in range(10, 0, -1): print(i)
  5. break exits the loop completely; continue skips only the current iteration

Day 9 Worksheet

  1. print() only displays output; return sends a value back to be used/stored elsewhere
  2. def square(n): return n ** 2
  3. It lets a function accept any number of positional arguments, collected as a tuple
  4. cube = lambda x: x ** 3
  5. def final_price(price, tax_rate=0.18): return price + price*tax_rate

Test 3

  1. if n > 0: print("positive") elif n < 0: print("negative") else: print("zero")
  2. 1, 3, 5
  3. i=0; while i<3: print("Processing..."); i+=1; print("Done")
  4. def is_even(n): return n % 2 == 0
  5. def find_max(numbers): m = numbers[0]; for n in numbers: if n > m: m = n; return m
  6. f(5) โ†’ 15; f(5,20) โ†’ 25
  7. big = lambda x: x > 100; list(filter(big, [50,150,99,200])) โ†’ [150, 200]

Day 10 Worksheet

  1. "w" overwrites existing content; "a" adds to the end
  2. It automatically closes the file even if an error occurs, preventing resource leaks
  3. Picks and returns one random item from the list
  4. with open("log.txt","w") as f: f.write("Test")
  5. datetime

Day 11 Worksheet

  1. Code inside finally always runs, whether or not an exception occurred โ€” used for cleanup
  2. It refers to the specific object instance calling the method, giving access to its own attributes
  3. try: n = int(input()); print(10/n) except ZeroDivisionError: print("Can't divide by zero")
  4. A class is the blueprint/template; an object is a specific instance created from that blueprint
  5. class Book:\n  def __init__(self, title, author):\n    self.title = title\n    self.author = author

Day 12 Worksheet

  1. It calls the parent class's constructor, so the child can reuse the parent's initialization logic
  2. class Animal:\n  def speak(self): print("Some sound")\nclass Dog(Animal):\n  def speak(self): print("Woof")
  3. False โ€” Python supports multiple inheritance (a class can inherit from more than one parent)
  4. It lets subclasses customize or specialize behavior inherited from a parent class

Final Test

  1. with open("data.txt","a") as f: f.write("New entry")
  2. ValueError
  3. try: a=int(input()); b=int(input()); print(a/b) except ZeroDivisionError: print("Cannot divide by zero") finally: print("Done")
  4. class Shape:\n  def __init__(self, name): self.name = name\n  def describe(self): print(self.name)
  5. class Circle(Shape):\n  def __init__(self, radius): super().__init__("Circle"); self.radius = radius\n  def describe(self): super().describe(); print(math.pi * self.radius**2)
  6. def get_evens(nums): return [n for n in nums if n % 2 == 0]
  7. {x: x**3 for x in range(1,6)}
  8. List: ordered, mutable, use for changeable collections. Tuple: ordered, immutable, use for fixed data. Dictionary: key-based lookup, use when data needs labels rather than positions.