Python Practice: 27 Exercises With Solutions for Beginners
Article

Python Practice: 27 Exercises With Solutions for Beginners

In this post
  1. How to Practice So It Sticks
  2. Level 1: Basics (8 exercises)
  3. Exercise 1: Convert Celsius to Fahrenheit
  4. Exercise 2: Even or odd
  5. Exercise 3: Largest of three numbers
  6. Exercise 4: Count the vowels
  7. Exercise 5: Palindrome check
  8. Exercise 6: FizzBuzz
  9. Exercise 7: Sum of the digits
  10. Exercise 8: Multiplication table
  11. Level 2: Lists, dictionaries and sets (8 exercises)
  12. Exercise 9: Second largest number
  13. Exercise 10: Remove duplicates and keep the order
  14. Exercise 11: Word frequency
  15. Exercise 12: Group words by first letter
  16. Exercise 13: Minimum and maximum as a tuple
  17. Exercise 14: Common elements of two lists
  18. Exercise 15: Flatten a list of lists
  19. Exercise 16: Rotate a list
  20. Level 3: Functions, files and errors (8 exercises)
  21. Exercise 17: Primes up to n
  22. Exercise 18: Fibonacci numbers
  23. Exercise 19: Anagram check
  24. Exercise 20: Handle errors safely
  25. Exercise 21: Total by category from CSV text
  26. Exercise 22: Read JSON data
  27. Exercise 23: Password strength checker
  28. Exercise 24: Binary search
  29. Level 4: Small projects (3 exercises)
  30. Exercise 25: Bank account class
  31. Exercise 26: Student grade report
  32. Exercise 27: Text analyser: top words
  33. Run the Self Checks
  34. A Simple Four Week Practice Plan
  35. What to do When You Are Stuck?
  36. Learning Python

Reading about Python does not make you good at it. Writing code does. This guide gives you Python practice that builds skill step by step: 27 exercises in four levels, from simple numbers and strings to lists, dictionaries, files, errors and a few small projects. Every exercise has a short problem, a hint you can open when you are stuck, a full solution, and self checks you can run to see whether your own answer works.

Most practice pages give you a problem and a solution and leave you to guess whether your answer is right. This guide fixes that. Every solution was run, its real output is shown, and the downloadable starter file contains the same exercises as empty functions with 70 self checks. You write the code, run the file, and it tells you how many checks pass. When all 70 pass, you have solved all 27. We also kept the exercises in a difficulty order, added the topics that other pages often skip (tuples, sets, error handling, CSV and JSON), and ended with small projects that join the pieces together.

A note on method. The most useful way to use this page is to try each problem on your own first, then read the hint, then run the self checks, and only then open the solution. Reading solutions without trying them feels like progress, but it does not build the skill. If you are still learning the syntax, read the Prwatech Python notes for beginners (link when live) and the Python classes and objects guide (link when live) alongside this page. All code was tested on Python 3.13. The only feature that needs an older minimum is math.isqrt, which needs Python 3.8 or later.

How to Practice So It Sticks

Diagram of the four practice levels in this guide, from Level 1 basics to Level 4 small projects, shown as steps going up
A five step way to practise each exercise
Step What to do Why
1. Read the problem Say it in your own words. Write down one example input and the answer you expect If you cannot state the answer, you cannot test your code
2. Try it alone Write code, even if it is wrong or slow Struggling is how the idea sticks
3. Use the hint Open the hint only after a real attempt A hint should unblock you, not do the work
4. Run the self checks Run the starter file and read which checks fail A failing check shows where your thinking is off
5. Compare Read the solution and ask what is different and why You learn a second way to solve it

Come back to an exercise a few days later and solve it again without looking. That second attempt shows you what you really learned. This is our suggestion for a method, and not a figure from a study.

Level 1: Basics (8 exercises)

These exercises use only numbers, text, comparisons, loops and functions. If you can write them without looking, you have the core of Python.

Exercise 1: Convert Celsius to Fahrenheit

Problem: Write celsius_to_fahrenheit(c) that returns the temperature in Fahrenheit, rounded to 1 decimal place. The formula is c times 9 divided by 5, plus 32.

Hint: Use multiplication and division, then round().

python
def celsius_to_fahrenheit(c):
    return round(c * 9 / 5 + 32, 1)

print(celsius_to_fahrenheit(0))
print(celsius_to_fahrenheit(100))
print(celsius_to_fahrenheit(-40))
print(celsius_to_fahrenheit(37))
output
32.0
212.0
-40.0
98.6

Exercise 2: Even or odd

Problem: Write is_even(n) that returns True if n is even and False if it is odd. It must work for 0 and for negative numbers.

Hint: The remainder operator % gives the remainder after division.

python
def is_even(n):
    return n % 2 == 0

print(is_even(7))
print(is_even(10))
print(is_even(0))
print(is_even(-4))
output
False
True
True
True

Exercise 3: Largest of three numbers

Problem: Write largest(a, b, c) that returns the largest of three numbers without using the built in max().

Hint: Compare a with b and c first. If a is not the largest, compare b with c.

python
def largest(a, b, c):
    if a >= b and a >= c:
        return a
    if b >= c:
        return b
    return c

print(largest(3, 9, 5))
print(largest(10, 2, 7))
print(largest(4, 4, 1))
print(largest(-3, -9, -5))
output
9
10
4
-3

Exercise 4: Count the vowels

Problem: Write count_vowels(text) that returns how many vowels (a, e, i, o, u) are in the text. Ignore upper and lower case.

Hint: Convert the text to lower case first, then count the characters that are in the string 'aeiou'.

python
def count_vowels(text):
    return sum(1 for ch in text.lower() if ch in "aeiou")

print(count_vowels("Prwatech Python"))
print(count_vowels("rhythm"))
print(count_vowels("AEIOU"))
output
3
0
5

Exercise 5: Palindrome check

Problem: Write is_palindrome(text) that returns True if the text reads the same forwards and backwards. Ignore case, spaces and punctuation.

Hint: Keep only letters and digits (the isalnum() method helps), lower case them, then compare the result with its reverse. A string reversed is text[::-1].

python
def is_palindrome(text):
    clean = "".join(ch.lower() for ch in text if ch.isalnum())
    return clean == clean[::-1]

print(is_palindrome("Madam"))
print(is_palindrome("A man, a plan, a canal: Panama"))
print(is_palindrome("Python"))
output
True
True
False

Exercise 6: FizzBuzz

Problem: Write fizzbuzz(n) that returns a list for the numbers 1 to n. For each number, use 'Fizz' if it divides by 3, 'Buzz' if it divides by 5, 'FizzBuzz' if it divides by both, and the number as a string otherwise.

Hint: Test the 'both' case first, otherwise a number like 15 stops at the first matching rule.

python
def fizzbuzz(n):
    out = []
    for i in range(1, n + 1):
        if i % 15 == 0:
            out.append("FizzBuzz")
        elif i % 3 == 0:
            out.append("Fizz")
        elif i % 5 == 0:
            out.append("Buzz")
        else:
            out.append(str(i))
    return out

print(fizzbuzz(15))
output
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz']

Exercise 7: Sum of the digits

Problem: Write sum_of_digits(n) that returns the sum of the digits of an integer. A negative number should give the same answer as its positive form.

Hint: Convert the absolute value to a string, then loop over the characters and convert each back to an integer.

python
def sum_of_digits(n):
    return sum(int(d) for d in str(abs(n)))

print(sum_of_digits(2026))
print(sum_of_digits(-405))
print(sum_of_digits(0))
output
10
9
0

Exercise 8: Multiplication table

Problem: Write multiplication_table(n, upto=5) that returns a list of strings like '7 x 1 = 7' for 1 up to upto.

Hint: Use a loop or a list comprehension with an f string, such as f'{n} x {i} = {n * i}'.

python
def multiplication_table(n, upto=5):
    return [f"{n} x {i} = {n * i}" for i in range(1, upto + 1)]

print(multiplication_table(7, 3))
output
['7 x 1 = 7', '7 x 2 = 14', '7 x 3 = 21']

Level 2: Lists, dictionaries and sets (8 exercises)

These exercises use the data structures you will use in almost every program. Notice how often a dictionary or a set turns a long loop into a short one.

Exercise 9: Second largest number

Problem: Write second_largest(nums) that returns the second largest distinct number in a list, or None if there is no such number.

Hint: A set removes duplicates. Sort the distinct values and take the second from the end.

python
def second_largest(nums):
    distinct = sorted(set(nums))
    if len(distinct) < 2:
        return None
    return distinct[-2]

print(second_largest([4, 9, 2, 9, 7]))
print(second_largest([5, 5, 5]))
print(second_largest([1, 2]))
output
7
None
1

Exercise 10: Remove duplicates and keep the order

Problem: Write remove_duplicates(items) that returns a new list without repeated values, keeping the first occurrence of each in its original order.

Hint: A plain set loses the order. Use a set only to remember what you have already seen, and a list to collect the result.

python
def remove_duplicates(items):
    seen = set()
    result = []
    for item in items:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

print(remove_duplicates([3, 1, 3, 2, 1, 4]))
print(remove_duplicates(["a", "b", "a"]))
output
[3, 1, 2, 4]
['a', 'b']

Exercise 11: Word frequency

Problem: Write word_frequency(text) that returns a dictionary of how many times each word appears. Ignore case and the punctuation marks . , ! ?

Hint: Lower case the text, remove the punctuation, split it, and use dict.get(word, 0) + 1 to count.

python
def word_frequency(text):
    for mark in ".,!?":
        text = text.replace(mark, "")
    counts = {}
    for word in text.lower().split():
        counts[word] = counts.get(word, 0) + 1
    return counts

print(word_frequency("The cat and the hat. The end!"))
output
{'the': 3, 'cat': 1, 'and': 1, 'hat': 1, 'end': 1}

Exercise 12: Group words by first letter

Problem: Write group_by_first_letter(words) that returns a dictionary where each key is a lower case first letter and each value is the list of words that start with it, in the order given.

Hint: dict.setdefault(key, []) gives you the list for a key, creating an empty one if the key is new.

python
def group_by_first_letter(words):
    groups = {}
    for word in words:
        groups.setdefault(word[0].lower(), []).append(word)
    return groups

print(group_by_first_letter(["apple", "bat", "Ant", "ball", "cat"]))
output
{'a': ['apple', 'Ant'], 'b': ['bat', 'ball'], 'c': ['cat']}

Exercise 13: Minimum and maximum as a tuple

Problem: Write min_max(nums) that returns the smallest and largest numbers as a tuple. Then unpack the result into two variables.

Hint: A function can return two values separated by a comma. Python packs them into a tuple, and you can unpack it with low, high = …

python
def min_max(nums):
    return min(nums), max(nums)

low, high = min_max([14, 3, 27, 8])

print((low, high))
print(min_max([5]))
output
(3, 27)
(5, 5)

Exercise 14: Common elements of two lists

Problem: Write common_elements(a, b) that returns a sorted list of the values that appear in both lists, with no repeats.

Hint: Turn both lists into sets and use the & operator, then sort the result.

python
def common_elements(a, b):
    return sorted(set(a) & set(b))

print(common_elements([1, 2, 2, 3, 4], [2, 4, 4, 6]))
print(common_elements(["x"], ["y"]))
output
[2, 4]
[]

Exercise 15: Flatten a list of lists

Problem: Write flatten(nested) that turns a list of lists, such as [[1, 2], [3], [4, 5]], into one list. Only one level of nesting needs to work.

Hint: A list comprehension can have two for clauses: the outer loop over the sublists, then the inner loop over the items.

python
def flatten(nested):
    return [item for sub in nested for item in sub]

print(flatten([[1, 2], [3], [4, 5]]))
print(flatten([[], [7]]))
output
[1, 2, 3, 4, 5]
[7]

Exercise 16: Rotate a list

Problem: Write rotate_list(items, k) that moves the last k items to the front and returns a new list. k can be larger than the list length.

Hint: Use k % len(items) so a large k wraps around, then join two slices: items[-k:] and items[:-k]. Take care of the empty list and of k equal to 0.

python
def rotate_list(items, k):
    if not items:
        return []
    k = k % len(items)
    if k == 0:
        return list(items)
    return items[-k:] + items[:-k]

print(rotate_list([1, 2, 3, 4, 5], 2))
print(rotate_list([1, 2, 3], 7))
print(rotate_list([], 3))
output
[4, 5, 1, 2, 3]
[3, 1, 2]
[]

Level 3: Functions, files and errors (8 exercises)

These exercises read data from text, handle bad input and use classic algorithms. They look like the small tasks that appear in analyst and developer tests.

Exercise 17: Primes up to n

Problem: Write primes_up_to(n) that returns every prime number from 2 to n. Use a helper function is_prime.

Hint: A number is prime if no number from 2 up to its square root divides it. math.isqrt(n) gives the integer square root.

python
import math

def is_prime(n):
    if n < 2:
        return False
    for d in range(2, math.isqrt(n) + 1):
        if n % d == 0:
            return False
    return True

def primes_up_to(n):
    return [x for x in range(2, n + 1) if is_prime(x)]

print(primes_up_to(30))
print(is_prime(1))
print(is_prime(97))
output
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
False
True

Exercise 18: Fibonacci numbers

Problem: Write fibonacci(n) that returns the first n Fibonacci numbers as a list. The sequence starts 0, 1, and each next number is the sum of the previous two.

Hint: Keep two variables, a and b. Append a, then move on with a, b = b, a + b.

python
def fibonacci(n):
    result = []
    a, b = 0, 1
    for _ in range(n):
        result.append(a)
        a, b = b, a + b
    return result

print(fibonacci(10))
print(fibonacci(1))
print(fibonacci(0))
output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
[0]
[]

Exercise 19: Anagram check

Problem: Write is_anagram(a, b) that returns True if the two texts use the same letters the same number of times. Ignore case and spaces.

Hint: If you sort the letters of both texts after removing spaces, anagrams give equal lists.

python
def is_anagram(a, b):
    def letters(text):
        return sorted(text.replace(" ", "").lower())
    return letters(a) == letters(b)

print(is_anagram("Listen", "Silent"))
print(is_anagram("Dormitory", "Dirty room"))
print(is_anagram("Python", "Typhoo"))
output
True
True
False

Exercise 20: Handle errors safely

Problem: Write safe_divide(a, b) that returns a / b, or None if b is zero. Write parse_int(text, default=0) that returns int(text), or the default if the text is not a whole number.

Hint: Put the risky line inside try and catch only the specific errors: ZeroDivisionError and ValueError.

python
def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return None

def parse_int(text, default=0):
    try:
        return int(text)
    except ValueError:
        return default

print(safe_divide(10, 4))
print(safe_divide(5, 0))
print(parse_int("42"))
print(parse_int("4x2"))
print(parse_int("", default=-1))
output
2.5
None
42
0
-1

Exercise 21: Total by category from CSV text

Problem: Write total_by_category(csv_text) that reads CSV text with the columns category and amount, and returns a dictionary of the total amount for each category.

Hint: The csv module can read text if you wrap it in io.StringIO. csv.DictReader gives each row as a dictionary. Remember to convert the amount from text to a number.

python
import csv, io

def total_by_category(csv_text):
    totals = {}
    for row in csv.DictReader(io.StringIO(csv_text)):
        totals[row["category"]] = totals.get(row["category"], 0) + float(row["amount"])
    return totals

print(total_by_category("category,amount\nfood,120\ntravel,300\nfood,80"))
output
{'food': 200.0, 'travel': 300.0}

Exercise 22: Read JSON data

Problem: Write order_total(json_text) that reads a JSON list of orders, each with item, qty and price, and returns the total value (qty times price, added up).

Hint: json.loads turns JSON text into Python lists and dictionaries. Then loop and add.

python
import json

def order_total(json_text):
    orders = json.loads(json_text)
    return sum(o["qty"] * o["price"] for o in orders)

print(order_total('[{"item": "pen", "qty": 3, "price": 5}, {"item": "book", "qty": 1, "price": 120}]'))
output
135

Exercise 23: Password strength checker

Problem: Write password_strength(pw) that runs five checks: at least 8 characters, a lower case letter, an upper case letter, a digit, and a symbol (any character that is not a letter or digit). Return 'Strong' if all five pass, 'Medium' if 3 or 4 pass, and 'Weak' otherwise. This is a practice rule and not real security advice.

Hint: Use any() with a generator for each check, and add up the True values with sum().

python
def password_strength(pw):
    checks = [
        len(pw) >= 8,
        any(c.islower() for c in pw),
        any(c.isupper() for c in pw),
        any(c.isdigit() for c in pw),
        any(not c.isalnum() for c in pw),
    ]
    score = sum(checks)
    if score == 5:
        return "Strong"
    if score >= 3:
        return "Medium"
    return "Weak"

print(password_strength("abc"))
print(password_strength("Python123"))
print(password_strength("Pyth0n@2026"))
output
Weak
Medium
Strong

Exercise 24: Binary search

Problem: Write binary_search(sorted_list, target) that returns the index of the target in a sorted list, or -1 if it is not there. Do not use list.index().

Hint: Keep two positions, low and high. Check the middle item and throw away the half that cannot contain the target.

python
def binary_search(sorted_list, target):
    low, high = 0, len(sorted_list) - 1
    while low <= high:
        mid = (low + high) // 2
        if sorted_list[mid] == target:
            return mid
        if sorted_list[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

print(binary_search([2, 5, 8, 12, 16, 23], 12))
print(binary_search([2, 5, 8, 12, 16, 23], 7))
print(binary_search([], 1))
output
3
-1
-1

Level 4: Small projects (3 exercises)

These exercises join classes, dictionaries, sorting and error handling in one piece of work. Take your time with them.

Exercise 25: Bank account class

Problem: Create a class BankAccount with a balance that starts at 0. Add deposit(amount) and withdraw(amount). Both must raise ValueError if the amount is zero or negative, and withdraw must also raise ValueError if the balance is too low.

Hint: Store the balance in self.balance. Check the rules at the top of each method, and raise ValueError('message') when a rule is broken.

python
class BankAccount:
    def __init__(self):
        self.balance = 0

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

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

acct = BankAccount()
acct.deposit(500)
acct.withdraw(200)
print(acct.balance)
try:
    acct.withdraw(1000)
except ValueError as err:
    print("Error:", err)
output
300
Error: Insufficient balance

Exercise 26: Student grade report

Problem: Write grade_report(students) where students is a dictionary of name to list of marks. Return a list of strings in name order, such as 'Asha: average 80.0, grade A'. Grades: 75 or more is A, 60 to 74.99 is B, 40 to 59.99 is C, below 40 is D.

Hint: Loop over sorted(students). Work out the average with sum(marks) / len(marks), round it to 1 decimal place, then choose the grade with if and elif.

python
def grade_report(students):
    lines = []
    for name in sorted(students):
        marks = students[name]
        avg = round(sum(marks) / len(marks), 1)
        if avg >= 75:
            grade = "A"
        elif avg >= 60:
            grade = "B"
        elif avg >= 40:
            grade = "C"
        else:
            grade = "D"
        lines.append(f"{name}: average {avg}, grade {grade}")
    return lines

data = {"Ravi": [55, 62, 48], "Asha": [80, 70, 90], "Meena": [30, 35, 41]}
for line in grade_report(data):
    print(line)
output
Asha: average 80.0, grade A
Meena: average 35.3, grade D
Ravi: average 55.0, grade C

Exercise 27: Text analyser: top words

Problem: Write top_words(text, n=3) that returns the n most common words as a list of (word, count) tuples. Ignore case and the punctuation marks . , ! ? and break ties alphabetically.

Hint: collections.Counter counts items for you. To break ties, sort the pairs with the key (-count, word).

python
from collections import Counter

def top_words(text, n=3):
    for mark in ".,!?":
        text = text.replace(mark, "")
    counts = Counter(text.lower().split())
    ranked = sorted(counts.items(), key=lambda pair: (-pair[1], pair[0]))
    return ranked[:n]

print(top_words("Python is fun. Python is easy, and fun is good!"))
output
[('is', 3), ('fun', 2), ('python', 2)]

Run the Self Checks

Download python_practice_starter.py. It holds the 27 exercises as empty functions, each with the problem as a one line description. Write your solution inside each function, then run the file:

terminal
python python_practice_starter.py
output
Passed 0, still to do or failing 70

Until you write a function, its checks count as not done. As you solve exercises, the passed number goes up. We tested this: with only Exercise 1 solved correctly, the file reports four checks passed, because Exercise 1 has four checks. The file python_practice_solutions.py has every solution and a runner that checks all of them.

terminal
python python_practice_solutions.py
output
All 70 checks passed

The solutions file also prints the results of the project exercises (25 and 26) above the final message, so a clean run ends with the line shown here.

A Simple Four Week Practice Plan

A four week Python practice plan
Week Exercises Goal
1 Level 1 (Exercises 1 to 8) Be able to write loops, conditions and small functions without help
2 Level 2 (Exercises 9 to 16) Use lists, dictionaries, sets and tuples without thinking about the syntax
3 Level 3 (Exercises 17 to 24) Handle errors, read CSV and JSON text and write simple algorithms
4 Level 4 (Exercises 25 to 27), then redo five older ones Build small programs and test your memory

This plan is a suggestion and not a guarantee. If you can do one level in less time, move on. If an exercise takes much longer than you expected, that is a sign to revisit the topic, not to give up.

What to do When You Are Stuck?

  • Make the problem smaller. Solve it for one input by hand, then write the code that does the same steps.
  • Print what is happening. Add print() lines to see the value of each variable at each step.
  • Check the type. Many beginner errors come from mixing text and numbers. Use type(x) to check.
  • Read the error message from the bottom. The last line names the error and the lines above show where it happened.
  • Search the exact error text. Add the word Python and the name of the function.
  • Take a break. A short walk often solves a problem faster than staring at it.

Learning Python

If you want guided practice, feedback on your code and a structured path, Prwatech runs a Python course in Bangalore. Offline classes are held in Bangalore (BTM Layout) and Pune (Kharadi). Learners in other cities can join live online classes or study at their own pace. For the syllabus, batch dates and fees, please ask the Prwatech learning team through the demo class form below.

Learn about our Python Certification Course

Want to know more?

Explore our website or get in touch with our team for further information.

Call our Counselors ✆+91 8147111254