Python Practice Worksheet: Foundation Builder —
Fully Commented Solutions
Basics
Q1: Print your name, age, and favorite color.
# Assign three variables at once using multiple assignment
name, age, color = "Alice", 25, "Blue"
# Print out labels and the variable values (commas add spaces automatically)
print("Name:", name, "Age:", age, "Color:", color)
Q2: Add two numbers and print the result.
# Assign values to two variables
a, b = 5, 7
# Add the numbers together and print the result with a label
print("Sum:", a + b)
Q3: Swap two variables.
# Assign initial values to x and y
x, y = 10, 20
# Swap the values of x and y using tuple unpacking (no temp variable required)
x, y = y, x
# Print the swapped values to verify
print("x:", x, "y:", y)
Q4: Ask the user for their name and greet them.
# Ask the user to type their name; input() returns a string
name = input("Enter your name: ")
# Use an f-string to insert the typed name inside the greeting message
print(f"Hello, {name}")
Q5: Calculate the square of a number.
# Assign a number to the variable 'n'
n = 9
# Multiply the number by itself to get its square
square = n * n
# Print the result with a label
print("Square:", square)
Q6: Show examples of 5 different data types.
# Create values of common built-in types
a = 10 # int (integer number)
b = 3.14 # float (decimal number)
c = "Hello" # str (text/string)
d = True # bool (True/False)
e = None # NoneType (represents “no value”)
# Print the types to verify each variable's data type
print(type(a), type(b), type(c), type(d), type(e))
Q7: Find the remainder when one number is divided by another.
# Choose a dividend and a divisor
num, denom = 29, 5
# Use the modulus operator (%) to compute the remainder
rem = num % denom
# Display the remainder
print("Remainder:", rem)
Q8: Take two numbers and print their average.
# Two numbers
a, b = 8, 13
# Compute the average (sum divided by count 2)
avg = (a + b) / 2
# Show the average value
print("Average:", avg)
Q9: Ask the user for birth year and calculate their age.
# Read birth year as text, convert to int for arithmetic
birth_year = int(input("Year of Birth: "))
# Use a fixed current year for reproducibility in exercises
current_year = 2025
# Subtract to get age
age = current_year - birth_year
# Display the computed age
print("Age:", age)
Q10: Convert kilometers to miles.
# Read a distance in kilometers (float allows decimals)
km = float(input("Kilometers: "))
# Conversion factor: 1 km ≈ 0.621371 miles
miles = km * 0.621371
# Print rounded result for neatness
print("Miles:", round(miles, 2))
Control Statements
Q1: Check if a number is positive, negative, or zero.
# Input an integer from the user
n = int(input("Number: "))
# Use if/elif/else to compare n against zero
if n > 0:
print("Positive")
elif n < 0:
print("Negative")
else:
print("Zero")
Q2: Print numbers from 1 to 10 using a loop.
# range(1, 11) generates 1..10
for i in range(1, 11):
# end=" " keeps numbers on one line separated by spaces
print(i, end=" ")
# Finish with a newline
print()
Q3: Print even numbers from 1 to 20.
# Start at 2, step by 2 ⇒ 2, 4, 6, ..., 20
for i in range(2, 21, 2):
print(i, end=" ")
print()
Q4: Print the first 10 odd numbers.
# Start from 1 and count 10 odds
i, count = 1, 0
while count < 10:
print(i, end=" ")
i += 2 # next odd
count += 1 # track how many printed
print()
Q5: Calculate the sum of the first 10 natural numbers.
# Initialize running total
s = 0
# Add numbers 1..10
for i in range(1, 11):
s += i
print("Sum:", s)
Q6: Check if a number is divisible by 5.
# Read an integer
n = int(input("Number: "))
# Divisible by 5 if remainder is 0
if n % 5 == 0:
print("Divisible by 5")
else:
print("Not divisible by 5")
Q7: Check if a person is eligible to vote (>=18).
# Read age as an int
age = int(input("Age: "))
# Conditional expression prints one of two messages
print("Eligible" if age >= 18 else "Not eligible")
Q8: Print multiplication table of 5.
# Loop i from 1..10 and multiply by 5
for i in range(1, 11):
print(f"5 x {i} = {5 * i}")
Q9: Print all numbers divisible by 3 from 1 to 50.
# Check each number in the interval
for i in range(1, 51):
if i % 3 == 0: # only print multiples of 3
print(i, end=" ")
print()
Q10: Print 'Hello' 5 times.
# Repeat the body exactly five times
for _ in range(5):
print("Hello")
Lists
Q1: Create a list of 5 fruits and print each one.
# Define a list (ordered, mutable collection)
fruits = ["apple", "banana", "grape", "orange", "mango"]
# Loop through and print each item
for f in fruits:
print(f)
Q2: Create a list of 10 numbers and print the 5th element.
# A list with 10 integers
nums = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
# Index 4 accesses the 5th element (0-based indexing)
print(nums[4])
Q3: Replace the 3rd element in a list with 100.
# Start with a simple list
lst = [1, 2, 3, 4, 5]
# Replace the item at index 2 (the 3rd element)
lst[2] = 100
print(lst)
Q4: Append a new item to a list.
# Begin with two items
colors = ["red", "blue"]
# .append() adds to the end of the list
[Link]("green")
print(colors)
Q5: Remove the last item from a list.
# Create a sample list
items = [10, 20, 30, 40]
# .pop() removes and returns the last element
[Link]()
print(items)
Q6: Check if a name exists in a list.
# A list of strings
names = ["Alice", "Bob", "Cathy"]
# Membership test using 'in'
q = "Bob"
print(q in names)
Q7: Find the length of a list without using len().
# We'll count items manually
data = [5, 7, 9, 11]
count = 0
for _ in data: # runs once per element
count += 1
print("Length:", count)
Q8: Reverse a list using slicing.
# Original order
data = [1, 2, 3, 4, 5]
# data[::-1] makes a reversed copy
print(data[::-1])
Q9: Create a list with 5 numbers and print their sum.
# A list of numbers
nums = [2, 4, 6, 8, 10]
# Accumulate sum with a loop
total = 0
for n in nums:
total += n
print("Sum:", total)
Q10: Print only even numbers from a list.
# Mixed integers
nums = [1, 2, 3, 4, 5, 6, 7, 8]
# Build a filtered list of evens
evens = []
for n in nums:
if n % 2 == 0:
[Link](n)
print(evens)
Strings
Q1: Print the length of a string.
# A sample string
s = "Python"
# len() returns the number of characters in the string
print(len(s))
Q2: Convert a string to uppercase.
# Lowercase text
s = "hello"
# .upper() creates a new uppercase string
print([Link]())
Q3: Convert a string to lowercase.
# Uppercase text
s = "HELLO"
# .lower() creates a new lowercase string
print([Link]())
Q4: Count occurrences of a letter in a string.
# Text to search
s = "banana"
# .count("a") counts how many 'a' characters
print([Link]("a"))
Q5: Check if a substring exists in a string.
# Larger string
s = "I love Python"
# "Python" in s evaluates to True if found, else False
print("Python" in s)
Q6: Reverse a string using slicing.
# Any string
s = "Python"
# s[::-1] reverses the string via slicing (step -1)
print(s[::-1])
Q7: Concatenate two strings.
# Two strings
a, b = "Hello", "World"
# + concatenates strings
print(a + b)
Q8: Check if a string starts with 'Hello'.
# Sample
s = "Hello Dan"
# .startswith("Hello") checks the beginning
print([Link]("Hello"))
Q9: Replace 'Python' with 'Java' in 'I love Python'.
# Original sentence
s = "I love Python"
# .replace(old, new) returns a modified copy
print([Link]("Python", "Java"))
Q10: Split a string by spaces.
# A sentence
s = "I love Python"
# .split() splits on whitespace into a list of words
print([Link]())
For Loops
Q1: Print numbers from 1 to 20.
# Loop from 1 up to and including 20
for i in range(1, 21):
print(i)
Q2: Print the squares of numbers from 1 to 10.
# Compute i*i for each i from 1 to 10
for i in range(1, 11):
print(i * i)
Q3: Print the multiplication table of a number entered by the user.
# Read a base number as int
n = int(input("Number: "))
# Print n × 1..10
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")
Q4: Calculate the factorial of a number using a for loop.
# Read n
n = int(input("n: "))
# Start product at 1 (multiplicative identity)
f = 1
# Multiply 2 × 3 × ... × n
for i in range(2, n + 1):
f *= i
print(f)
Q5: Print all even numbers between 1 and 50.
# Step of 2 gives evens directly
for i in range(2, 51, 2):
print(i)
Q6: Find the sum of numbers from 1 to 100.
# Built-in sum() adds all values in the given range
total = sum(range(1, 101))
print(total)
Q7: Print each character in a string on a new line.
# The string to iterate
s = "Python"
# Loop yields one character at a time
for ch in s:
print(ch)
Q8: Print elements of a list using a for loop.
# A list to iterate over
lst = [10, 20, 30]
# Print each element of the list
for x in lst:
print(x)
Q9: Print numbers from 10 down to 1.
# Use a negative step in range to count backwards
for i in range(10, 0, -1):
print(i)
Q10: Calculate the sum of odd numbers from 1 to 50.
# Use a comprehension to pick odd numbers and sum them
total = sum([i for i in range(1, 51) if i % 2 != 0])
print(total)
Functions
Q1: Write a function that prints 'Hello World'.
# Define a function with no parameters
def hello():
# Function body runs when hello() is called
print("Hello World")
# Call the function
hello()
Q2: Write a function that adds two numbers.
# Function with two parameters a and b
def add(a, b):
# Return the sum to the caller
return a + b
# Print the result of calling add
print(add(3, 5))
Q3: Write a function that squares a number.
# One-parameter function
def square(n):
# Return n multiplied by itself
return n * n
print(square(9))
Q4: Write a function that returns the maximum of two numbers.
# Compare and return the larger value
def max2(a, b):
return a if a >= b else b
print(max2(10, 4))
Q5: Write a function that greets a person by name.
# Parameterized function that prints a greeting
def greet(name):
print("Hello,", name)
# Supply the argument "Dan"
greet("Dan")
Q6: Write a function that calculates the area of a rectangle.
# Compute area as width × height
def area(w, h):
return w * h
print(area(5, 3))
Q7: Write a function that converts kilometers to miles.
# Convert km to miles using constant factor
def km_to_miles(km):
return km * 0.621371
print(km_to_miles(10))
Q8: Write a function that checks if a number is even or odd.
# Return True if even, else False
def is_even(n):
return n % 2 == 0
print(is_even(7))
Q9: Write a function that prints the multiplication table of a number.
# Print the table inside the function
def table(n):
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")
# Example call
table(6)
Q10: Write a function that calculates factorial using a loop.
# Iterative factorial implementation
def fact(n):
f = 1
for i in range(2, n + 1):
f *= i
return f
print(fact(5))
Tuples
Q1: Create a tuple of 5 colors and print the first element.
# Tuples are immutable ordered collections
colors = ("red", "green", "blue", "yellow", "purple")
# Index the first element (0-based)
print(colors[0])
Q2: Print the last element of a tuple.
# Negative index -1 refers to the last element
colors = ("red", "green", "blue", "yellow", "purple")
print(colors[-1])
Q3: Check if an item exists in a tuple.
# Membership test on a tuple
colors = ("red", "green", "blue")
print("green" in colors)
Q4: Convert a tuple into a list.
# Define a tuple
t = (1, 2, 3)
# Convert to list to make it mutable
lst = list(t)
print(lst)
Q5: Concatenate two tuples.
# Two tuples to combine
a = (1, 2)
b = (3, 4)
# + returns a new tuple containing items of both
print(a + b)
Q6: Repeat a tuple three times.
# Replicate the tuple using *
t = ("A", "B")
print(t * 3)
Q7: Slice the first three elements from a tuple.
# Slicing works like with lists
t = (10, 20, 30, 40, 50)
print(t[:3])
Q8: Find the length of a tuple.
# len() on a tuple returns number of items
t = (1, 2, 3, 4)
print(len(t))
Q9: Count occurrences of an element in a tuple.
# .count(value) returns number of occurrences
t = (1, 2, 2, 3, 2, 4)
print([Link](2))
Q10: Find the index of an element in a tuple.
# .index(value) returns first index at which value appears
t = ("cat", "dog", "bird")
print([Link]("dog"))
Sets
Q1: Create a set of 5 numbers and print it.
# A set stores unique, unordered elements
s = {1, 2, 3, 4, 5}
print(s)
Q2: Add a new element to a set.
# Start with a set of three items
s = {1, 2, 3}
# .add(value) inserts one new element (no effect if already present)
[Link](4)
print(s)
Q3: Remove an element from a set.
# Remove a known element (raises KeyError if not present)
s = {1, 2, 3}
[Link](2)
print(s)
Q4: Check if an element exists in a set.
# Membership testing in sets is fast on average
s = {1, 2, 3}
print(2 in s)
Q5: Find the union of two sets.
# Union contains elements that are in either set
a = {1, 2}
b = {2, 3}
print(a | b) # '|' is the union operator
Q6: Find the intersection of two sets.
# Intersection contains elements common to both sets
a = {1, 2}
b = {2, 3}
print(a & b) # '&' is the intersection operator
Q7: Find the difference between two sets.
# Difference returns elements in 'a' that are not in 'b'
a = {1, 2, 3}
b = {2, 3}
print(a - b)
Q8: Convert a list with duplicates into a set.
# Converting to set removes duplicates automatically
lst = [1, 2, 2, 3]
print(set(lst))
Q9: Check the length of a set.
# len() returns the number of unique items
s = {1, 2, 3}
print(len(s))
Q10: Clear all elements from a set.
# .clear() removes all items, leaving an empty set
s = {1, 2, 3}
[Link]()
print(s)