.py file. The goal is to struggle a little โ that's how learning happens.Exercises 1โ5: The Basics
Exercise 1 โ Print & Variables
Create variables for your name, age, and city. Print a sentence using all three. Example output: Hi, I'm Uzair, 25 years old, from Lahore.
# Your solution:
name = ___
age = ___
city = ___
print(f"Hi, I'm {___}, {___} years old, from {___}.")
Show Answer
name = "Uzair"
age = 25
city = "Lahore"
print(f"Hi, I'm {name}, {age} years old, from {city}.")Exercise 2 โ User Input
Ask the user for two numbers and print their sum, difference, product, and quotient.
Show Answer
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print(f"Sum: {a + b}")
print(f"Diff: {a - b}")
print(f"Product: {a * b}")
if b != 0:
print(f"Quotient: {a / b}")
else:
print("Can't divide by zero!")Exercise 3 โ String Methods
Given the string " Hello, World! ", print it: (a) with whitespace stripped, (b) in uppercase, (c) with "World" replaced by "Python", (d) split into a list of words.
Show Answer
s = " Hello, World! "
print(s.strip())
print(s.strip().upper())
print(s.strip().replace("World", "Python"))
print(s.strip().split())Exercise 4 โ Number Properties
Ask the user for a number. Print whether it is: even or odd, positive/negative/zero, and divisible by 5.
Show Answer
n = int(input("Enter a number: "))
print("Even" if n % 2 == 0 else "Odd")
if n > 0: print("Positive")
elif n < 0: print("Negative")
else: print("Zero")
print("Divisible by 5" if n % 5 == 0 else "Not divisible by 5")Exercise 5 โ Temperature Converter
Ask for a temperature in Celsius. Convert it to Fahrenheit (F = C ร 9/5 + 32) and Kelvin (K = C + 273.15). Print all three.
Show Answer
c = float(input("Enter temperature in Celsius: "))
f = c * 9/5 + 32
k = c + 273.15
print(f"Celsius: {c}ยฐC")
print(f"Fahrenheit: {f:.2f}ยฐF")
print(f"Kelvin: {k:.2f}K")Exercises 6โ10: Control Flow & Loops
Exercise 6 โ FizzBuzz
Print numbers 1 to 50. But: print "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for both.
Show Answer
for i in range(1, 51):
if i % 15 == 0: print("FizzBuzz")
elif i % 3 == 0: print("Fizz")
elif i % 5 == 0: print("Buzz")
else: print(i)Exercise 7 โ Multiplication Table
Ask for a number and print its full multiplication table (1โ12).
Show Answer
n = int(input("Enter a number: "))
for i in range(1, 13):
print(f"{n} ร {i} = {n * i}")Exercise 8 โ Factorial
Calculate the factorial of a number entered by the user (e.g., 5! = 120). Use a loop, not math.factorial().
Show Answer
n = int(input("Enter a positive number: "))
result = 1
for i in range(1, n + 1):
result *= i
print(f"{n}! = {result}")Exercise 9 โ Star Patterns
Ask for a number n. Print a right-angle triangle of n rows made of stars. For n=4: row 1 has 1 star, row 2 has 2, etc.
Show Answer
n = int(input("Number of rows: "))
for i in range(1, n + 1):
print("*" * i)Exercise 10 โ Prime Checker
Write a program that checks if a number is prime. A prime is only divisible by 1 and itself (e.g., 2, 3, 5, 7, 11).
Show Answer
n = int(input("Check if this number is prime: "))
if n < 2:
print("Not prime")
else:
is_prime = True
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
is_prime = False
break
print("Prime!" if is_prime else f"Not prime (divisible by {i})")Exercises 11โ15: Functions & Data Structures
Exercise 11 โ List Statistics
Create a list of 10 numbers. Write functions (without using built-ins) to find: minimum, maximum, sum, and average.
Show Answer
def find_min(lst):
m = lst[0]
for x in lst:
if x < m: m = x
return m
def find_max(lst):
m = lst[0]
for x in lst:
if x > m: m = x
return m
def find_sum(lst):
s = 0
for x in lst: s += x
return s
nums = [5, 2, 8, 1, 9, 3, 7, 4, 6, 10]
print(f"Min: {find_min(nums)}")
print(f"Max: {find_max(nums)}")
print(f"Sum: {find_sum(nums)}")
print(f"Avg: {find_sum(nums)/len(nums)}")Exercise 12 โ Word Counter
Ask the user for a sentence. Count how many times each word appears. Print the results sorted by count (most frequent first).
Show Answer
sentence = input("Enter a sentence: ").lower()
words = sentence.split()
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
sorted_words = sorted(counts.items(), key=lambda x: x[1], reverse=True)
for word, count in sorted_words:
print(f"{word}: {count}")Exercise 13 โ Palindrome Checker
Write a function that checks if a string is a palindrome (reads the same forwards and backwards). Ignore spaces and capitalisation. E.g., "A man a plan a canal Panama" is a palindrome.
Show Answer
def is_palindrome(s):
cleaned = s.lower().replace(" ", "")
return cleaned == cleaned[::-1]
tests = ["racecar", "hello", "A man a plan a canal Panama", "level"]
for t in tests:
print(f'"{t}" โ {"Palindrome โ" if is_palindrome(t) else "Not palindrome โ"}')Exercise 14 โ Simple Contact Book
Build a contact book using a dictionary. Support commands: add, find, delete, list, quit.
Show Answer
contacts = {}
while True:
cmd = input("\nCommand (add/find/delete/list/quit): ").lower()
if cmd == "add":
name = input("Name: ")
phone = input("Phone: ")
contacts[name] = phone
print(f"Added {name}")
elif cmd == "find":
name = input("Search name: ")
print(contacts.get(name, "Not found"))
elif cmd == "delete":
name = input("Name to delete: ")
if name in contacts:
del contacts[name]
print(f"Deleted {name}")
else:
print("Not found")
elif cmd == "list":
if contacts:
for n, p in contacts.items(): print(f"{n}: {p}")
else:
print("No contacts")
elif cmd == "quit":
breakExercise 15 โ List Comprehension Practice
Using list comprehensions (one line each): (a) square numbers 1โ10, (b) filter even numbers from 1โ20, (c) convert a list of strings to uppercase, (d) get only words longer than 4 letters from a sentence.
Show Answer
# a) Squares 1-10
squares = [x**2 for x in range(1, 11)]
print(squares)
# b) Even numbers 1-20
evens = [x for x in range(1, 21) if x % 2 == 0]
print(evens)
# c) Uppercase
words = ["hello", "world", "python", "coding"]
upper = [w.upper() for w in words]
print(upper)
# d) Long words
sentence = "the quick brown fox jumps over the lazy dog"
long_words = [w for w in sentence.split() if len(w) > 4]
print(long_words)Exercises 16โ20: Mini Projects
Exercise 16 โ Caesar Cipher
Implement the Caesar cipher: shift each letter by a number (e.g., shift 3: AโD, BโE). Write encrypt and decrypt functions. Leave non-letters unchanged.
Show Answer
def caesar(text, shift, decrypt=False):
if decrypt: shift = -shift
result = ""
for ch in text:
if ch.isalpha():
base = ord('A') if ch.isupper() else ord('a')
result += chr((ord(ch) - base + shift) % 26 + base)
else:
result += ch
return result
msg = "Hello, World!"
enc = caesar(msg, 3)
dec = caesar(enc, 3, decrypt=True)
print(f"Original: {msg}")
print(f"Encrypted: {enc}")
print(f"Decrypted: {dec}")Exercise 17 โ Number System Converter
Write a program that converts a decimal number to binary, octal, and hexadecimal. Show the work step-by-step for binary (divide by 2 repeatedly).
Show Answer
n = int(input("Enter a decimal number: "))
print(f"Decimal: {n}")
print(f"Binary: {bin(n)[2:]}")
print(f"Octal: {oct(n)[2:]}")
print(f"Hexadecimal: {hex(n)[2:].upper()}")
# Manual binary conversion:
temp, bits = n, []
while temp > 0:
bits.append(temp % 2)
temp //= 2
print("\nBinary step-by-step:")
print(" โ ".join(str(b) for b in reversed(bits)))Exercise 18 โ Simple Bank Account Class
Create a BankAccount class with: deposit, withdraw (check for sufficient funds), get_balance, and transaction history. Test with multiple operations.
Show Answer
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
self.history = []
def deposit(self, amount):
self.balance += amount
self.history.append(f"+ยฃ{amount:.2f}")
print(f"Deposited ยฃ{amount:.2f}. Balance: ยฃ{self.balance:.2f}")
def withdraw(self, amount):
if amount > self.balance:
print(f"Insufficient funds! Balance: ยฃ{self.balance:.2f}")
return False
self.balance -= amount
self.history.append(f"-ยฃ{amount:.2f}")
print(f"Withdrew ยฃ{amount:.2f}. Balance: ยฃ{self.balance:.2f}")
return True
def statement(self):
print(f"\n=== {self.owner}'s Account ===")
for t in self.history: print(t)
print(f"Balance: ยฃ{self.balance:.2f}")
acc = BankAccount("Uzair", 1000)
acc.deposit(500)
acc.withdraw(200)
acc.withdraw(2000)
acc.statement()Exercise 19 โ File-based Scoreboard
Build a high score tracker that saves scores to a file. Allow: adding a score (name + score), viewing top 5, clearing the board. Scores persist between program runs.
Show Answer
import json, os
SCORES_FILE = "scores.json"
def load_scores():
if os.path.exists(SCORES_FILE):
with open(SCORES_FILE) as f:
return json.load(f)
return []
def save_scores(scores):
with open(SCORES_FILE, "w") as f:
json.dump(scores, f)
scores = load_scores()
while True:
cmd = input("\nadd/top/clear/quit: ").lower()
if cmd == "add":
name = input("Name: ")
score = int(input("Score: "))
scores.append({"name": name, "score": score})
save_scores(scores)
print("Saved!")
elif cmd == "top":
top5 = sorted(scores, key=lambda x: x["score"], reverse=True)[:5]
print("\n=== TOP 5 ===")
for i, s in enumerate(top5, 1):
print(f"{i}. {s['name']}: {s['score']}")
elif cmd == "clear":
scores = []
save_scores(scores)
print("Cleared!")
elif cmd == "quit":
breakExercise 20 โ Text Adventure Game
Build a simple text adventure: 3 rooms (Start, Forest, Cave), items to pick up, a monster to defeat, and a win condition. Use a dictionary for the game world.
Show Answer
world = {
"start": {
"desc": "You are in a dimly lit room. There is a SWORD on the floor.",
"items": ["sword"],
"exits": {"north": "forest"}
},
"forest": {
"desc": "A dark forest. You hear growling to the EAST.",
"items": ["torch"],
"exits": {"south": "start", "east": "cave"}
},
"cave": {
"desc": "A cave with a DRAGON! You need a sword to win!",
"items": [],
"exits": {"west": "forest"}
}
}
location = "start"
inventory = []
print("=== DRAGON QUEST ===\n")
while True:
room = world[location]
print(f"\n{room['desc']}")
if room["items"]: print(f"Items here: {', '.join(room['items'])}")
print(f"Exits: {', '.join(room['exits'].keys())}")
cmd = input("\n> ").lower().strip()
if cmd in room["exits"]:
location = room["exits"][cmd]
if location == "cave":
if "sword" in inventory:
print("\nYou slay the dragon with your sword! YOU WIN! ๐")
break
elif cmd.startswith("take "):
item = cmd[5:]
if item in room["items"]:
inventory.append(item)
room["items"].remove(item)
print(f"Picked up {item}.")
else:
print(f"No {item} here.")
elif cmd == "inventory":
print(f"Inventory: {inventory or 'empty'}")
elif cmd == "quit":
break
else:
print("Try: north/south/east/west, take [item], inventory, quit")