Skip to content

Python Exercises for Beginners (With Solutions)

Updated 11 min read Aimerscrew

Reading about code is a good start, but you only really learn Python by writing it. This page collects 25 Python exercises for beginners, each with a sample output and a tested solution. They start easy and get a little harder in every section, so you can work through them in order or jump straight to the topic you want to practice.

🌍 Real-life example

Learning to code is like learning to cook. You can watch a hundred recipe videos, but you only get good once you chop the onions yourself and burn a few pancakes. These exercises are your kitchen: small, everyday dishes like a tip calculator, a shipping-cost rule or a word counter that you cook from scratch.

How to use these Python exercises

Each exercise has a short problem statement, an example of what your program should print, and a link to the lesson that teaches the idea. The solution is hidden behind a Show solution button.

  1. Read the problem and write your own solution in a file or an online editor.
  2. Run it and compare your output with the example.
  3. Only then open the solution. Your code doesn't have to match mine; if the output is right, your answer is right.
Roadmap of the exercise topics in order of difficulty: basics, strings, conditionals, loops, lists, dictionaries, functions, files and OOP, with difficulty growing from easy to harder
The exercises follow the tutorial: each topic builds on the ones before it.

💡 Tip

Stuck for more than 15 minutes? Reread the linked lesson, then try again. Struggling a bit is normal; it's exactly the part where learning happens.

Basics exercises

1. Restaurant tip calculator

A dinner bill is $48.50. Calculate an 18% tip and the total, and print both with two decimal places. Related lesson: arithmetic operators.

Tip: $8.73
Total: $57.23
Show solution
bill = 48.50
tip = bill * 0.18
total = bill + tip

print(f"Tip: ${tip:.2f}")
print(f"Total: ${total:.2f}")
Tip: $8.73
Total: $57.23

2. Celsius to Fahrenheit

Convert 25 degrees Celsius to Fahrenheit using the formula F = C × 9 / 5 + 32. Related lesson: Python numbers.

25 C is 77.0 F
Show solution
celsius = 25
fahrenheit = celsius * 9 / 5 + 32
print(f"{celsius} C is {fahrenheit} F")
25 C is 77.0 F

3. Movie length in hours and minutes

A movie runs for 135 minutes. Print its length as hours and minutes. Hint: use floor division // and modulus %. Related lesson: arithmetic operators.

2 h 15 min
Show solution
runtime = 135
hours = runtime // 60
minutes = runtime % 60
print(hours, "h", minutes, "min")
2 h 15 min

String exercises

4. Get someone's initials

Given the full name "grace brewster hopper", print the initials in uppercase with a dot after each letter. Related lesson: string methods.

G.B.H.
Show solution
full_name = "grace brewster hopper"
initials = ""
for word in full_name.split():
    initials += word[0].upper() + "."
print(initials)
G.B.H.

5. Count the vowels

Count how many vowels (a, e, i, o, u) are in the sentence "Coffee keeps the world turning". Upper and lower case should both count. Related lesson: Python strings.

Vowels: 9
Show solution
sentence = "Coffee keeps the world turning"
count = 0
for letter in sentence.lower():
    if letter in "aeiou":
        count += 1
print("Vowels:", count)
Vowels: 9

6. Palindrome checker

A palindrome reads the same forwards and backwards. Check whether "Racecar" is one, ignoring upper and lower case. Related lesson: string slicing.

True
Show solution
word = "Racecar"
cleaned = word.lower()
print(cleaned == cleaned[::-1])
True

The slice [::-1] steps through the string backwards, which gives you a reversed copy.

7. Hide a card number

Online stores show only the last four digits of a card. Turn "4111222233334444" into stars followed by the last four digits, keeping the same total length. Related lessons: string slicing and f-strings.

************4444
Show solution
card = "4111222233334444"
masked = "*" * (len(card) - 4) + card[-4:]
print(masked)
************4444

Conditional exercises

8. Even or odd

For each number in 7, 12, 0, print whether it is even or odd. Related lesson: if-else.

7 is odd
12 is even
0 is even
Show solution
for number in [7, 12, 0]:
    if number % 2 == 0:
        print(number, "is even")
    else:
        print(number, "is odd")
7 is odd
12 is even
0 is even

9. Free shipping rule

An online shop charges $5.99 shipping, but shipping is free for orders of $50 or more. Print the shipping cost for an order of $42.00 and one of $65.50. Related lesson: if-else.

Order $42.00 -> shipping $5.99
Order $65.50 -> shipping $0.00
Show solution
for order in [42.00, 65.50]:
    if order >= 50:
        shipping = 0
    else:
        shipping = 5.99
    print(f"Order ${order:.2f} -> shipping ${shipping:.2f}")
Order $42.00 -> shipping $5.99
Order $65.50 -> shipping $0.00

10. Leap year

A year is a leap year if it is divisible by 4, except years divisible by 100, unless they are also divisible by 400. Check 2024, 1900 and 2000. Related lesson: logical operators.

2024 True
1900 False
2000 True
Show solution
for year in [2024, 1900, 2000]:
    is_leap = (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
    print(year, is_leap)
2024 True
1900 False
2000 True

Loop exercises

11. Add up 1 to 100

Use a loop to add every whole number from 1 to 100. Related lesson: range().

5050
Show solution
total = 0
for number in range(1, 101):
    total += number
print(total)
5050

Once it works, try the one-line version: print(sum(range(1, 101))).

12. Times table

Print the 7 times table from 1 to 5, lined up neatly. Related lesson: for loop.

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
Show solution
for i in range(1, 6):
    print(f"7 x {i} = {7 * i}")
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

13. FizzBuzz

The classic interview warm-up. 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. Related lesson: nested if.

1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
Show solution
for n in range(1, 16):
    if n % 15 == 0:
        print("FizzBuzz", end=" ")
    elif n % 3 == 0:
        print("Fizz", end=" ")
    elif n % 5 == 0:
        print("Buzz", end=" ")
    else:
        print(n, end=" ")
print()
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

Check 15 first. If you check 3 first, 15 prints "Fizz" and never reaches the FizzBuzz branch.

14. Savings goal

You have $200 saved and add $75 every month. Use a while loop to find how many months it takes to reach $1,000. Related lesson: while loop.

Goal reached after 11 months with $1025
Show solution
savings = 200
months = 0
while savings < 1000:
    savings += 75
    months += 1
print(f"Goal reached after {months} months with ${savings}")
Goal reached after 11 months with $1025

List exercises

15. Weekly temperature report

Given the daily highs [18, 21, 19, 24, 26, 22, 20], print the highest, the lowest and the average rounded to one decimal place. Related lesson: Python lists.

High: 26
Low: 18
Average: 21.4
Show solution
temps = [18, 21, 19, 24, 26, 22, 20]
print("High:", max(temps))
print("Low:", min(temps))
print("Average:", round(sum(temps) / len(temps), 1))
High: 26
Low: 18
Average: 21.4

16. Remove duplicate songs

A playlist has repeats. Remove the duplicates but keep the songs in their original order. Related lesson: list methods.

['Yellow', 'Halo', 'Clocks', 'Hello']
Show solution
playlist = ["Yellow", "Halo", "Yellow", "Clocks", "Halo", "Hello"]
unique = []
for song in playlist:
    if song not in unique:
        unique.append(song)
print(unique)
['Yellow', 'Halo', 'Clocks', 'Hello']

Converting to a set also removes duplicates, but sets don't keep the order.

17. Squares of even numbers

From the numbers 1 to 10, build a list of the squares of only the even numbers, using one list comprehension. Related lesson: list comprehension.

[4, 16, 36, 64, 100]
Show solution
squares = [n * n for n in range(1, 11) if n % 2 == 0]
print(squares)
[4, 16, 36, 64, 100]

Dictionary exercises

18. Word frequency

Count how many times each word appears in "the cat and the hat and the bat". Related lesson: Python dictionaries.

{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}
Show solution
text = "the cat and the hat and the bat"
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1
print(counts)
{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}

19. Menu price lookup

A café menu is stored in a dictionary. Print the price of a latte, and print "Not on the menu" for a matcha, without causing an error. Related lesson: dictionary methods.

Latte: 4.5
Matcha: Not on the menu
Show solution
menu = {"espresso": 3.0, "latte": 4.5, "mocha": 5.25}
print("Latte:", menu.get("latte", "Not on the menu"))
print("Matcha:", menu.get("matcha", "Not on the menu"))
Latte: 4.5
Matcha: Not on the menu

20. Merge two shopping carts

Two family members filled separate carts. Combine them into one dictionary, adding the quantities of items that appear in both. Related lesson: dictionary methods.

{'apples': 6, 'milk': 1, 'bread': 2, 'eggs': 12}
Show solution
cart_a = {"apples": 4, "milk": 1, "bread": 1}
cart_b = {"apples": 2, "bread": 1, "eggs": 12}

merged = dict(cart_a)
for item, qty in cart_b.items():
    merged[item] = merged.get(item, 0) + qty
print(merged)
{'apples': 6, 'milk': 1, 'bread': 2, 'eggs': 12}

Function exercises

21. Is it a prime number?

Write a function is_prime(n) that returns True if n is a prime number (only divisible by 1 and itself). Use it to list the primes below 30. Related lesson: Python functions.

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Show solution
def is_prime(n):
    if n < 2:
        return False
    for divisor in range(2, int(n ** 0.5) + 1):
        if n % divisor == 0:
            return False
    return True

print([n for n in range(30) if is_prime(n)])
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

You only need to test divisors up to the square root of n: if n had a bigger factor, it would also have a smaller one you already tested.

22. Order summary with a default argument

Write a function order_total(price, quantity=1, discount=0) that returns the total after a percentage discount. Call it three different ways. Related lesson: function arguments.

12.0
36.0
32.4
Show solution
def order_total(price, quantity=1, discount=0):
    subtotal = price * quantity
    return round(subtotal * (1 - discount / 100), 2)

print(order_total(12.0))
print(order_total(12.0, 3))
print(order_total(12.0, 3, discount=10))
12.0
36.0
32.4

23. Average of any number of scores

Write a function average(*scores) that accepts any number of scores and returns their average, or 0 if no scores are given. Related lesson: *args and **kwargs.

85.0
0
Show solution
def average(*scores):
    if not scores:
        return 0
    return sum(scores) / len(scores)

print(average(90, 80, 85))
print(average())
85.0
0

File and OOP exercises

24. Save and count your tasks

Write three tasks to a file called tasks.txt, one per line. Then read the file back and print each task with a number. Related lessons: writing files and the with statement.

1. Buy groceries
2. Call the dentist
3. Water the plants
Show solution
tasks = ["Buy groceries", "Call the dentist", "Water the plants"]

with open("tasks.txt", "w") as file:
    for task in tasks:
        file.write(task + "\n")

with open("tasks.txt") as file:
    for number, line in enumerate(file, start=1):
        print(f"{number}. {line.strip()}")
1. Buy groceries
2. Call the dentist
3. Water the plants

strip() removes the newline at the end of each line, so you don't get blank lines between tasks.

25. A bank account class

Create a BankAccount class with an owner and a balance. Add deposit() and withdraw() methods; withdraw() should raise a ValueError if there isn't enough money. Related lessons: classes and objects and raise.

Mia has $150
Error: Insufficient funds
Mia has $150
Show solution
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError("Insufficient funds")
        self.balance -= amount

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


account = BankAccount("Mia", 100)
account.deposit(50)
print(account)

try:
    account.withdraw(500)
except ValueError as error:
    print("Error:", error)

print(account)
Mia has $150
Error: Insufficient funds
Mia has $150

The __str__ method controls what print(account) shows. You'll find more methods like it in magic methods.

Common mistakes when solving exercises

1. Printing instead of returning

If an exercise says a function should return a value, use return. A function that only prints gives back None:

def double(n):
    print(n * 2)

result = double(4)
print(result)
8
None

Read more in the return statement.

2. Off-by-one ranges

range(1, 100) stops at 99, not 100. The end value is never included, so use range(1, 101) to reach 100.

3. Comparing text without normalizing it

print("Racecar" == "racecaR")
print("Racecar".lower() == "racecaR".lower())
False
True

Python compares strings exactly, including case. Use .lower() (and often .strip()) before comparing.

4. Peeking at the solution too early

The most common mistake isn't in the code at all. If you read the answer before trying, it feels easy, but you won't remember it tomorrow. Give every problem a real attempt first.

Final challenge

🏋️ Try it yourself

Combine everything: write a function grade_report(scores) that takes a dictionary of student names and scores, and returns a new dictionary mapping each name to a letter grade (A for 90+, B for 80+, C for 70+, F otherwise). Print the report for {"Ava": 93, "Leo": 78, "Zoe": 85, "Max": 64}.

Show solution
def letter_grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    return "F"

def grade_report(scores):
    return {name: letter_grade(score) for name, score in scores.items()}

report = grade_report({"Ava": 93, "Leo": 78, "Zoe": 85, "Max": 64})
for name, grade in report.items():
    print(f"{name}: {grade}")
Ava: A
Leo: C
Zoe: B
Max: F

What's next?

Feeling more confident? Put your knowledge to the test with the top Python interview questions and answers, a great way to review the theory behind everything you just practiced.

Key takeaways

  • The fastest way to learn Python is to solve small problems yourself before reading the solution.
  • Start with basics and strings, then move on to conditionals, loops, lists and dictionaries.
  • Functions, files and classes build on everything before them, so practice them last.
  • If your output matches the example, your solution is correct, even if it looks different from mine.
  • Watch for classic slips: printing instead of returning, off-by-one ranges and case-sensitive comparisons.
  • When you get stuck, reread the linked lesson and try again before opening the answer.

Frequently asked questions

How can a beginner practice Python?

Solve small, focused exercises every day, starting with variables and strings and moving on to loops, lists, dictionaries and functions. Write the code yourself, run it, and only compare with a solution after you have tried.

How many Python exercises should I do per day?

Two or three exercises a day is plenty for most beginners. Steady daily practice beats a long session once a week, because you keep revisiting ideas before you forget them.

What are good first Python exercises?

Good first exercises use everyday logic: a tip calculator, a temperature converter, counting vowels, checking even or odd numbers, FizzBuzz and adding up a list of numbers.

Is it bad to look at the solution?

No, as long as you try first. Looking at a solution after an honest attempt shows you a new approach. Looking before trying makes the problem feel easy without teaching you much.

Where can I practice Python online for free?

You can solve these exercises in any free online Python editor or in the IDLE editor that comes with Python. After that, try the quizzes on this site to check your understanding.