Beginner to Intermediate โ A Self-Paced, Printable Course
Daily lessons ยท Hands-on tasks ยท Paper worksheets ยท Test sheets with answer key
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!
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.
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
" " or ' ' is treated as text (a string), not code.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)
my_var โ
2var โ| Type | Example | Meaning |
|---|---|---|
int | 10 | Whole number |
float | 3.14 | Decimal number |
str | "hello" | Text |
bool | True / False | Logical value |
Use type() to check any variable's data type:
print(type(10)) # <class 'int'>
print(type("hi")) # <class 'str'>
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
Open a Python environment (IDLE, VS Code, or an online compiler like replit.com). Write a script that:
type() of each of those three variables.type(7.0) return?
1st_place = "gold"
My name is Ananya using a variable called name.
print("5" + "5")? Explain why.
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)
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
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.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")
Write a small "BMI-style" calculator:
input().float.bmi = weight / (height ** 2)round(bmi, 2).17 // 5 evaluate to?
17 % 5 evaluate to?
"3.9" into a float and add 0.1 to it. Write the code.
input() always return, regardless of what the user types?
(4 > 2) and (3 == 4)
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
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
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)
Write a program that takes a sentence as input and:
.split())text[::-1])"Your sentence had X words."s = "Pharmacy", what is s[2:5]?
"HELLO" to lowercase.
"cat" in "concatenate" return?
Name: Ananya, Age: 20 using variables n and a.
len("VCMC") return?
Basics, Operators, Strings โ 30 minutes, closed book
print(type(3 / 1))?
/ and //?
is_active set to True.
10 % 3 + 2 ** 2
x = "42", write code to convert it to an integer and print x + 8 correctly.
s = "Molecular Cipher", write the code to print only "Molecular" using slicing.
"abc".upper().replace("A", "X") return?
"Total: 45.00" from a variable total = 45, formatted to 2 decimal places.
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
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)
for fruit in fruits:
print(fruit)
# with index
for i, fruit in enumerate(fruits):
print(i, fruit)
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
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]
Create a list of 5 subjects/skills you're learning. Then:
.append()enumerate()nums = [3, 1, 4, 1, 5], what does nums[1:3] return?
.remove() and .pop()?
sorted([4,2,8,1], reverse=True) return?
colors = ["red","blue","green"] along with its index.
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)
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)
| Type | Ordered? | Mutable? | Duplicates? |
|---|---|---|---|
| List | Yes | Yes | Allowed |
| Tuple | Yes | No | Allowed |
| Set | No | Yes | Not allowed |
Create two sets of ingredients for two "recipes" (5 items each, with at least 2 overlapping). Print:
s = {1, 2, 2, 3, 3, 3}, what does print(s) output?
a = {1,2,3} and b = {3,4,5}, write the result of a.intersection(b).
my_set[0]? Why or why not?
coords = (10, 20, 30) into variables x, y, z.
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)
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
for key, value in student.items():
print(f"{key}: {value}")
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']}")
Build a mini "contact book":
input() and use .get() to safely look them up (print "Not found" if missing).d = {"a": 1, "b": 2}, write code to safely get the value of key "c" with a default of 0.
"gpa": 8.5 to a dictionary called student.
d.items() return?
d = {"x": 10, "y": 20}.
Lists, Tuples, Sets, Dictionaries โ 35 minutes, closed book
lst = [10, 20, 30, 40], write code to print the list in reverse order without using .reverse().
range(1, 20).
my_tuple[0] = 5?
a = {1,2,3,4} and b = {3,4,5,6}, write the union and the difference (a - b).
book with keys "title", "author", "year". Then print a sentence using all three values in one f-string.
data = {"a": [1,2,3], "b": [4,5,6]}, write code to print the second item of the list stored under key "b".
[45, 88, 67, 92, 34, 76]. Write code to print only the scores above 60, using a list comprehension.
marks = 78
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Fail")
{} to define code blocks. This is not optional โ incorrect indentation causes errors.age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("ID required")
else:
print("Underage")
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")
age = 17
status = "Adult" if age >= 18 else "Minor"
print(status)
Write a simple grading system:
input()if x > 0: sign = "positive" else: sign = "non-positive"
x = 15; what prints? if x > 20: print("big") elif x > 10: print("medium") else: print("small")
print("yes" if 5 == 5.0 else "no")?
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)
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
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
for i in range(3):
for j in range(3):
print(f"i={i}, j={j}")
Write a program that:
for loopwhile loop to keep asking the user for a password until they type "python123" correctlybreak to stop a loop early when a target number is found in a listrange(3, 15, 3) generate?
while loop without updating its condition variable?
for i in range(5): if i==3: continue; print(i)
break and continue?
def greet(name):
print(f"Hello, {name}!")
greet("Ananya") # calling the function
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.def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25 (uses default exponent)
print(power(5, 3)) # 125
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")
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
Write these functions:
is_prime(n) โ returns True/False if n is a prime numberaverage(*nums) โ accepts any number of arguments and returns their averagemap() on a list of temperaturesprint() and return inside a function?
square(n) that returns n squared.
*args allow a function to do?
def cube(x): return x ** 3
tax_rate=0.18 that calculates final price from a base price.
Conditionals, Loops, Functions โ 35 minutes, closed book
for i in range(1,6): if i%2==0: continue; print(i)
is_even(n) that returns True if n is even, False otherwise.
find_max(numbers) that returns the largest number in a list, without using max().
def f(x, y=10): return x + y then print(f(5)) and print(f(5, 20))?
filter() on the list [50, 150, 99, 200].
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())
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).
# 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().| Mode | Meaning |
|---|---|
"r" | Read (file must exist) |
"w" | Write (overwrites existing content) |
"a" | Append (adds to end) |
Write a program that:
random module to generate 5 random numbers between 1-100numbers.txt, one per line"w" and "a" file modes?
with open(...) as f: preferred over manually opening/closing a file?
import random followed by random.choice([1,2,3]) do?
log.txt.
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.")
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}")
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.Create a class BankAccount with:
__init__(self, owner, balance=0)deposit(amount) that adds to balancewithdraw(amount) that raises a ValueError if amount > balancefinally block?
self represent inside a class method?
ZeroDivisionError when dividing 10 by a user-input number.
Book with attributes title and author set in __init__.
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
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.
Build a "Contact Manager" console app that combines everything:
Contact with name, phone, emailsuper().__init__() do?
Animal with a method speak() that prints "Some sound", then a class Dog(Animal) that overrides speak() to print "Woof".
Modules, Files, Exceptions, OOP โ 45 minutes, closed book
Shape with an __init__ that stores a name, and a method describe() that prints it.
Circle(Shape) that inherits from Shape above, adds a radius, and overrides describe() to also print the area (use math.pi).
{x: x**3 for x in range(1,6)} is the answer style โ write your own from scratch first!)
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.
<class 'float'>first_place = "gold" (or any name not starting with a digit)name = "Ananya"; print("My name is " + name)"55" โ with strings, + joins (concatenates) them rather than adding numbers32float("3.9") + 0.1str (string), alwaysFalse (True and False โ False)"arm""HELLO".lower()Truef"Name: {n}, Age: {a}"4<class 'float'>/ gives a precise (float) result; // gives the floored (rounded-down whole) resultis_active = True10 % 3 = 1, 2**2 = 4, total = 5x = "42"; print(int(x) + 8) โ 50print(s[0:9])"XBC"total = 45; print(f"Total: {total:.2f}")[1, 4].remove() deletes by value; .pop() deletes by index (default: last item) and returns it[x**2 for x in range(1,6)][8, 4, 2, 1]for i, c in enumerate(colors): print(i, c){1, 2, 3}{3}x, y, z = coordsd.get("c", 0)student["gpa"] = 8.5dict_items([('a',1),('b',2)])for k, v in d.items(): print(k, v)print(lst[::-1])[x for x in range(1,20) if x % 2 == 0]{1,2,3,4,5,6}; Difference (a-b): {1,2}book = {"title": "...", "author": "...", "year": 2024}; print(f"{book['title']} by {book['author']} ({book['year']})")print(data["b"][1])[s for s in [45,88,67,92,34,76] if s > 60]IndentationError / TabError โ stay consistent (spaces recommended)sign = "positive" if x > 0 else "non-positive""medium" (15 is not > 20, but is > 10)if n % 3 == 0 and n % 5 == 0:"yes" โ Python treats 5 == 5.0 as True3, 6, 9, 120, 1, 2, 4 (3 is skipped)for i in range(10, 0, -1): print(i)break exits the loop completely; continue skips only the current iterationprint() only displays output; return sends a value back to be used/stored elsewheredef square(n): return n ** 2cube = lambda x: x ** 3def final_price(price, tax_rate=0.18): return price + price*tax_rateif n > 0: print("positive") elif n < 0: print("negative") else: print("zero")1, 3, 5i=0; while i<3: print("Processing..."); i+=1; print("Done")def is_even(n): return n % 2 == 0def find_max(numbers): m = numbers[0]; for n in numbers: if n > m: m = n; return mf(5) โ 15; f(5,20) โ 25big = lambda x: x > 100; list(filter(big, [50,150,99,200])) โ [150, 200]"w" overwrites existing content; "a" adds to the endwith open("log.txt","w") as f: f.write("Test")datetimefinally always runs, whether or not an exception occurred โ used for cleanuptry: n = int(input()); print(10/n) except ZeroDivisionError: print("Can't divide by zero")class Book:\n def __init__(self, title, author):\n self.title = title\n self.author = authorclass Animal:\n def speak(self): print("Some sound")\nclass Dog(Animal):\n def speak(self): print("Woof")with open("data.txt","a") as f: f.write("New entry")ValueErrortry: a=int(input()); b=int(input()); print(a/b) except ZeroDivisionError: print("Cannot divide by zero") finally: print("Done")class Shape:\n def __init__(self, name): self.name = name\n def describe(self): print(self.name)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)def get_evens(nums): return [n for n in nums if n % 2 == 0]{x: x**3 for x in range(1,6)}