TExcelTAD
Home › Python › Python Exercises

Python Exercises

Time to practise! Each exercise below has a starter playground: it runs as-is and prints a placeholder result, so you can see the expected format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" line. If you get stuck, open the solution — but try for a few minutes first.

# Exercise Topics
1 Temperature table loops, f-strings
2 Vowel counter strings, membership
3 FizzBuzz if/elif, modulo
4 Word frequency dictionaries, split
5 Palindrome checker slicing, string methods
6 Grade report lists, functions, comprehensions
7 Flatten and deduplicate recursion, sets
8 Bank account class classes, exceptions

1. Temperature table

Print a conversion table from Celsius to Fahrenheit for 0, 10, 20, 30 and 40 °C. Use the formula F = C × 9/5 + 32 and format each row as 0 C = 32.0 F (Celsius right-aligned in 3 characters, Fahrenheit in 5 with 1 decimal).

Expected first line: 0 C = 32.0 F, last line: 40 C = 104.0 F.

python · try it yourself
# TODO: loop over the Celsius values and print each row
for c in [0]:
    f = 0.0  # TODO: use the formula
    print(c, "C =", f, "F")
0 C = 0.0 F
Show solution
python
for c in range(0, 41, 10):
    f = c * 9 / 5 + 32
    print(f"{c:3} C = {f:5.1f} F")

2. Vowel counter

Write count_vowels(text) that returns how many vowels (a e i o u, upper or lower case) a string contains.

Expected: count_vowels("Programming in Python") == 5.

python · try it yourself
def count_vowels(text):
    # TODO: count the vowels
    return 0

print(count_vowels("Programming in Python"))
print(count_vowels("AEIOU xyz"))
0
0
Show solution
python
def count_vowels(text):
    return sum(1 for ch in text.lower() if ch in "aeiou")

print(count_vowels("Programming in Python"))   # 5
print(count_vowels("AEIOU xyz"))               # 5

3. FizzBuzz

For the numbers 1 to 15, print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number otherwise. Print them on one line separated by spaces.

Expected: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

python · try it yourself
results = []
for n in range(1, 16):
    # TODO: append "Fizz", "Buzz", "FizzBuzz" or the number
    results.append(str(n))
print(" ".join(results))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Show solution
python
results = []
for n in range(1, 16):
    if n % 15 == 0:
        results.append("FizzBuzz")
    elif n % 3 == 0:
        results.append("Fizz")
    elif n % 5 == 0:
        results.append("Buzz")
    else:
        results.append(str(n))
print(" ".join(results))

Checking n % 15 first matters: otherwise 15 would be caught by the % 3 branch.

4. Word frequency

Count how often each word appears in the text (ignore case and the punctuation . and ,), then print the three most common words with their counts, most frequent first. For equal counts, keep the order in which the words first appeared.

Expected:

text
the: 4
cat: 2
and: 2
python · try it yourself
text = "The cat and the dog. The cat sat, and the dog ran."

counts = {}
# TODO: clean the text, split it into words and count them

for word, n in list(counts.items())[:3]:
    print(f"{word}: {n}")
print(len(counts), "distinct words")
0 distinct words
Show solution
python
text = "The cat and the dog. The cat sat, and the dog ran."

counts = {}
cleaned = text.lower().replace(".", "").replace(",", "")
for word in cleaned.split():
    counts[word] = counts.get(word, 0) + 1

top = sorted(counts.items(), key=lambda kv: kv[1], reverse=True)
for word, n in top[:3]:
    print(f"{word}: {n}")
print(len(counts), "distinct words")   # 6 distinct words

sorted is stable, so words with equal counts stay in first-seen order. collections.Counter(cleaned.split()).most_common(3) gives the same result.

5. Palindrome checker

A palindrome reads the same forwards and backwards, ignoring case, spaces and punctuation. Write is_palindrome(text).

Expected: True, False, True.

python · try it yourself
def is_palindrome(text):
    # TODO: keep only letters/digits, lowercase them, compare with the reverse
    return False

print(is_palindrome("Racecar"))
print(is_palindrome("Python"))
print(is_palindrome("Was it a car or a cat I saw?"))
False
False
False
Show solution
python
def is_palindrome(text):
    letters = "".join(ch.lower() for ch in text if ch.isalnum())
    return letters == letters[::-1]

print(is_palindrome("Racecar"))                       # True
print(is_palindrome("Python"))                        # False
print(is_palindrome("Was it a car or a cat I saw?"))  # True

6. Grade report

Given a dictionary of students and their scores, write report(scores) that returns a list of lines "Name: average (letter)", sorted by average from highest to lowest. Letter grades: A ≥ 90, B ≥ 80, C ≥ 70, otherwise F. Round averages to 1 decimal place.

Expected:

text
Mai: 92.3 (A)
Long: 81.0 (B)
Tien: 64.7 (F)
python · try it yourself
scores = {
    "Long": [78, 85, 80],
    "Mai": [95, 88, 94],
    "Tien": [60, 72, 62],
}

def letter(avg):
    # TODO
    return "?"

def report(scores):
    # TODO: compute averages, sort, format
    return [f"{name}: ?" for name in scores]

for line in report(scores):
    print(line)
Long: ?
Mai: ?
Tien: ?
Show solution
python
def letter(avg):
    if avg >= 90:
        return "A"
    if avg >= 80:
        return "B"
    if avg >= 70:
        return "C"
    return "F"

def report(scores):
    averages = {name: sum(s) / len(s) for name, s in scores.items()}
    ranked = sorted(averages.items(), key=lambda kv: kv[1], reverse=True)
    return [f"{name}: {avg:.1f} ({letter(avg)})" for name, avg in ranked]

7. Flatten and deduplicate

Write unique_flat(nested) that takes a list which may contain nested lists to any depth and returns a sorted list of the unique numbers inside.

Expected: [1, 2, 3, 5, 8].

python · try it yourself
def unique_flat(nested):
    # TODO: walk the structure (recursion helps), collect numbers in a set
    return []

print(unique_flat([3, [1, 2, [3, 5]], [[8], 1], 2]))
[]
Show solution
python
def unique_flat(nested):
    found = set()

    def walk(items):
        for item in items:
            if isinstance(item, list):
                walk(item)
            else:
                found.add(item)

    walk(nested)
    return sorted(found)

print(unique_flat([3, [1, 2, [3, 5]], [[8], 1], 2]))

8. Bank account class

Create a BankAccount class with an owner, a balance (starting at 0), and methods deposit(amount) and withdraw(amount). Both must raise ValueError for amounts ≤ 0, and withdraw must raise ValueError("insufficient funds") if the balance is too low. Add a __str__ that returns "Owner: balance" formatted with 2 decimals.

Expected:

text
Hanh: 70.00
Error: insufficient funds
Error: amount must be positive
Hanh: 70.00
python · try it yourself
class BankAccount:
    def __init__(self, owner):
        self.owner = owner
        # TODO: balance

    # TODO: deposit, withdraw, __str__

acct = BankAccount("Hanh")
print(acct.owner)
Hanh
Show solution
python
class BankAccount:
    def __init__(self, owner):
        self.owner = owner
        self.balance = 0.0

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("amount must be positive")
        self.balance += amount

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("amount must be positive")
        if amount > self.balance:
            raise ValueError("insufficient funds")
        self.balance -= amount

    def __str__(self):
        return f"{self.owner}: {self.balance:.2f}"

acct = BankAccount("Hanh")
acct.deposit(100)
acct.withdraw(30)
print(acct)
for action, amount in [(acct.withdraw, 500), (acct.deposit, -5)]:
    try:
        action(amount)
    except ValueError as err:
        print("Error:", err)
print(acct)

Test yourself

In FizzBuzz, why must the n % 15 == 0 check come before n % 3 == 0?

  1. It's faster
  2. Otherwise multiples of 15 would match the % 3 branch first and print only Fizz
  3. Python requires larger numbers first
  4. It doesn't matter

Which expression reverses the string s?

  1. s.reverse()
  2. reversed(s)
  3. s[::-1]
  4. s[-1:]

Which tool is ideal for collecting unique values?

  1. list
  2. tuple
  3. set
  4. str