
Python Exercises: 71 Practice Problems with Solutions
Reading Python is easy; writing it is what makes it stick. Every problem below is small enough to finish in a few minutes and specific enough to teach one idea — string slicing, dictionary grouping, recursion, binary search.
Use the editor below to run your answer. It executes real Python, so you will see the same tracebacks you would get on your own machine.
Run your answer here
Type your solution, press Run, and use the Input box when a problem asks you to read from standard input.
How to practise so it actually sticks
Attempt the problem before opening the solution, even if your first version is clumsy. A working ugly answer teaches more than a beautiful one you read. When you get stuck for more than five minutes, read the hint — not the solution — and try again.
After you pass, open the solution and ask what is different about it. Shorter? Fewer variables? A built-in you did not know? That comparison is where most of the growth happens. Then change the problem slightly: sort the other direction, handle an empty input, read a value instead of hard-coding it.
Aim for three to five problems a day rather than thirty in one sitting. Spacing practice over days is what moves syntax from "I can look it up" to "my fingers know it".
The exercises
Showing 71 of 71 exercises.
- BeginnerBasics & output
1. Greet a name
Store the name "Ada" in a variable and print "Hello, Ada!".
Hint: Use an f-string: f"Hello, {name}!".
name = # print the greetingShow solution
name = "Ada" print(f"Hello, {name}!") - BeginnerBasics & output
2. Swap two variables
Given a = 3 and b = 8, swap them and print both.
Hint: Python can unpack a tuple: a, b = b, a.
a, b = 3, 8Show solution
a, b = 3, 8 a, b = b, a print(a, b) - BeginnerBasics & output
3. Print the type of each value
Print the type of 5, 5.0, "5" and True, one per line.
Hint: type(x) returns the class; print it directly.
values = [5, 5.0, "5", True]Show solution
for v in [5, 5.0, "5", True]: print(type(v)) - BeginnerBasics & output
4. Multi-line receipt
Print a three-line receipt with an item name, a quantity and a total, aligned with tabs.
Hint: \t inserts a tab, \n a new line.
Show solution
print("Item\tQty\tTotal") print("Pens\t3\t45") print("Books\t1\t250") - BeginnerBasics & output
5. Add two numbers from input
Read two lines of input, convert them to integers and print the sum. (Use the Input box in the editor.)
Hint: input() returns text, so wrap it with int().
a = int(input())Show solution
a = int(input()) b = int(input()) print(a + b) - BeginnerStrings
6. Reverse a string
Print "programming" backwards.
Hint: Slicing with a negative step: text[::-1].
text = "programming"Show solution
text = "programming" print(text[::-1]) - BeginnerStrings
7. Count the vowels
Count how many vowels appear in "play with coding".
Hint: Loop over the characters and test membership in "aeiou".
text = "play with coding"Show solution
text = "play with coding" count = sum(1 for ch in text if ch in "aeiou") print(count) - BeginnerStrings
8. Clean up a messy name
Turn " kARAN aRORA " into "Karan Arora".
Hint: Chain .strip() and .title().
raw = " kARAN aRORA "Show solution
raw = " kARAN aRORA " print(raw.strip().title()) - IntermediateStrings
9. Palindrome check
Report whether "Never odd or even" is a palindrome, ignoring case and spaces.
Hint: Remove spaces, lowercase it, then compare with the reversed version.
phrase = "Never odd or even"Show solution
phrase = "Never odd or even" clean = phrase.replace(" ", "").lower() print(clean == clean[::-1]) - IntermediateStrings
10. Longest word
Print the longest word in a sentence and its length.
Hint: max(words, key=len) picks the longest.
sentence = "learning python opens many doors"Show solution
sentence = "learning python opens many doors" word = max(sentence.split(), key=len) print(word, len(word)) - IntermediateStrings
11. Character frequency
Print how many times each letter appears in "mississippi", most frequent first.
Hint: collections.Counter has a most_common() method.
from collections import CounterShow solution
from collections import Counter for ch, n in Counter("mississippi").most_common(): print(ch, n) - AdvancedStrings
12. Caesar cipher
Shift every lowercase letter of "attack at dawn" forward by 3 places and print the result.
Hint: Use ord() and chr() with modulo 26 so z wraps to c.
msg = "attack at dawn" shift = 3Show solution
msg = "attack at dawn" shift = 3 out = "" for ch in msg: if ch.isalpha(): out += chr((ord(ch) - 97 + shift) % 26 + 97) else: out += ch print(out) - BeginnerNumbers & math
13. Even or odd
Print whether 47 is even or odd.
Hint: The remainder operator % gives 0 for even numbers.
n = 47Show solution
n = 47 print("even" if n % 2 == 0 else "odd") - BeginnerNumbers & math
14. Area of a circle
Print the area of a circle of radius 7, rounded to two decimals.
Hint: math.pi and round(value, 2).
import math r = 7Show solution
import math r = 7 print(round(math.pi * r ** 2, 2)) - BeginnerNumbers & math
15. Celsius to Fahrenheit table
Print a table of 0, 10, 20 ... 100 degrees Celsius with their Fahrenheit values.
Hint: F = C * 9 / 5 + 32; range(0, 101, 10) steps by ten.
Show solution
for c in range(0, 101, 10): print(c, c * 9 / 5 + 32) - IntermediateNumbers & math
16. Factorial with a loop
Compute 10! without using the math module.
Hint: Start at 1 and multiply through range(1, 11).
result = 1Show solution
result = 1 for i in range(1, 11): result *= i print(result) - IntermediateNumbers & math
17. Is it prime?
Decide whether 97 is prime.
Hint: Test divisors up to the square root only.
n = 97Show solution
n = 97 prime = n > 1 and all(n % d for d in range(2, int(n ** 0.5) + 1)) print(prime) - IntermediateNumbers & math
18. Sum of digits
Add up the digits of 98765.
Hint: Convert to a string and sum the int() of each character.
n = 98765Show solution
n = 98765 print(sum(int(d) for d in str(n))) - AdvancedNumbers & math
19. Greatest common divisor
Find the GCD of 252 and 105 using Euclid's algorithm (no imports).
Hint: Repeat a, b = b, a % b until b is 0.
a, b = 252, 105Show solution
a, b = 252, 105 while b: a, b = b, a % b print(a) - AdvancedNumbers & math
20. Binary and hex
Print 255 in binary, octal and hexadecimal without the 0b/0o/0x prefixes.
Hint: format(n, 'b'), 'o' and 'x'.
n = 255Show solution
n = 255 print(format(n, "b"), format(n, "o"), format(n, "x")) - BeginnerConditionals
21. Grade from a score
Print A for 90+, B for 75-89, C for 60-74 and F below 60, for a score of 82.
Hint: Chain if / elif / else, checking the highest band first.
score = 82Show solution
score = 82 if score >= 90: print("A") elif score >= 75: print("B") elif score >= 60: print("C") else: print("F") - BeginnerConditionals
22. Largest of three
Print the largest of 14, 9 and 23 without using max().
Hint: Keep a 'best so far' variable and compare.
a, b, c = 14, 9, 23Show solution
a, b, c = 14, 9, 23 best = a if b > best: best = b if c > best: best = c print(best) - IntermediateConditionals
23. Leap year
Decide whether 2100 is a leap year.
Hint: Divisible by 4 and not by 100, unless also divisible by 400.
y = 2100Show solution
y = 2100 print(y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)) - IntermediateConditionals
24. Ticket pricing rules
Price a ticket: free under 5, 100 for ages 5-17, 250 for 18-59, 120 for 60+. Print the price for age 63.
Hint: Order the branches from the youngest band upward.
age = 63Show solution
age = 63 if age < 5: price = 0 elif age < 18: price = 100 elif age < 60: price = 250 else: price = 120 print(price) - IntermediateConditionals
25. FizzBuzz
Print 1 to 20, replacing multiples of 3 with Fizz, of 5 with Buzz and of both with FizzBuzz.
Hint: Check the 15 case first.
Show solution
for i in range(1, 21): if i % 15 == 0: print("FizzBuzz") elif i % 3 == 0: print("Fizz") elif i % 5 == 0: print("Buzz") else: print(i) - BeginnerLoops
26. Times table
Print the 7 times table from 7x1 to 7x10.
Hint: range(1, 11) with an f-string.
Show solution
for i in range(1, 11): print(f"7 x {i} = {7 * i}") - BeginnerLoops
27. Sum 1 to 100
Add every number from 1 to 100 with a loop and print the total.
Hint: Accumulate into a total variable starting at 0.
total = 0Show solution
total = 0 for i in range(1, 101): total += i print(total) - BeginnerLoops
28. Star triangle
Print a right-angled triangle of stars five rows tall.
Hint: A string times a number repeats it: "*" * 3.
Show solution
for i in range(1, 6): print("*" * i) - BeginnerLoops
29. While-loop countdown
Count down from 5 to 1 with a while loop, then print "Go!".
Hint: Decrease the counter inside the loop or it never ends.
n = 5Show solution
n = 5 while n > 0: print(n) n -= 1 print("Go!") - IntermediateLoops
30. continue and break
Print numbers 1 to 20 but skip multiples of 4 and stop entirely at 17.
Hint: continue skips one turn, break exits the loop.
Show solution
for i in range(1, 21): if i == 17: break if i % 4 == 0: continue print(i) - IntermediateLoops
31. Coordinate grid
Print every (row, column) pair of a 3x3 grid using nested loops.
Hint: Put one for loop inside another.
Show solution
for r in range(3): for c in range(3): print(r, c) - IntermediateLoops
32. Fibonacci sequence
Print the first 12 Fibonacci numbers.
Hint: Keep two variables and reassign them together.
a, b = 0, 1Show solution
a, b = 0, 1 for _ in range(12): print(a) a, b = b, a + b - AdvancedLoops
33. Collatz steps
Count how many steps 27 takes to reach 1 under the Collatz rule (halve if even, else 3n+1).
Hint: Use a while loop with a step counter.
n = 27 steps = 0Show solution
n = 27 steps = 0 while n != 1: n = n // 2 if n % 2 == 0 else 3 * n + 1 steps += 1 print(steps) - BeginnerLists & tuples
34. Add and remove items
Start from ["a", "b"], append "c", remove "a" and print the list.
Hint: .append() adds to the end, .remove() deletes by value.
items = ["a", "b"]Show solution
items = ["a", "b"] items.append("c") items.remove("a") print(items) - BeginnerLists & tuples
35. Min, max and average
Print the smallest, largest and average of [12, 7, 30, 5, 18].
Hint: sum(nums) / len(nums) gives the average.
nums = [12, 7, 30, 5, 18]Show solution
nums = [12, 7, 30, 5, 18] print(min(nums), max(nums), sum(nums) / len(nums)) - BeginnerLists & tuples
36. Slice practice
From range(1, 11) as a list, print the first three, the last three and every second item.
Hint: nums[:3], nums[-3:], nums[::2].
nums = list(range(1, 11))Show solution
nums = list(range(1, 11)) print(nums[:3]) print(nums[-3:]) print(nums[::2]) - IntermediateLists & tuples
37. Squares of even numbers
Build a list of the squares of the even numbers from 1 to 20 in one line.
Hint: [x ** 2 for x in range(1, 21) if x % 2 == 0].
Show solution
print([x ** 2 for x in range(1, 21) if x % 2 == 0]) - IntermediateLists & tuples
38. Remove duplicates, keep order
Remove duplicates from [3, 1, 3, 7, 1, 9] while keeping the original order.
Hint: Track what you have seen in a set as you loop.
nums = [3, 1, 3, 7, 1, 9]Show solution
nums = [3, 1, 3, 7, 1, 9] seen = set() out = [] for n in nums: if n not in seen: seen.add(n) out.append(n) print(out) - IntermediateLists & tuples
39. Sort tuples by second value
Sort [("pen", 45), ("book", 250), ("bag", 120)] by price, cheapest first.
Hint: sorted(data, key=lambda item: item[1]).
data = [("pen", 45), ("book", 250), ("bag", 120)]Show solution
data = [("pen", 45), ("book", 250), ("bag", 120)] print(sorted(data, key=lambda item: item[1])) - AdvancedLists & tuples
40. Flatten a nested list
Turn [[1, 2], [3, 4], [5]] into [1, 2, 3, 4, 5].
Hint: A comprehension can carry two for clauses.
grid = [[1, 2], [3, 4], [5]]Show solution
grid = [[1, 2], [3, 4], [5]] print([x for row in grid for x in row]) - AdvancedLists & tuples
41. Transpose a matrix
Transpose [[1, 2, 3], [4, 5, 6]] so rows become columns.
Hint: zip(*matrix) pairs the columns together.
m = [[1, 2, 3], [4, 5, 6]]Show solution
m = [[1, 2, 3], [4, 5, 6]] print([list(row) for row in zip(*m)]) - BeginnerDictionaries & sets
42. Build a student record
Create a dictionary with name, age and course, then print each key and value.
Hint: Loop with .items().
student = {}Show solution
student = {"name": "Ada", "age": 19, "course": "Python"} for key, value in student.items(): print(key, value) - BeginnerDictionaries & sets
43. Safe lookups
Look up a missing key without crashing and print a default of 0 instead.
Hint: prices.get("tea", 0).
prices = {"coffee": 80}Show solution
prices = {"coffee": 80} print(prices.get("tea", 0)) - IntermediateDictionaries & sets
44. Invert a dictionary
Swap keys and values of {"a": 1, "b": 2, "c": 3}.
Hint: A dict comprehension: {v: k for k, v in d.items()}.
d = {"a": 1, "b": 2, "c": 3}Show solution
d = {"a": 1, "b": 2, "c": 3} print({v: k for k, v in d.items()}) - IntermediateDictionaries & sets
45. Group words by first letter
Group ["apple", "avocado", "banana", "cherry", "blueberry"] into a dictionary keyed by first letter.
Hint: setdefault(letter, []).append(word).
words = ["apple", "avocado", "banana", "cherry", "blueberry"]Show solution
words = ["apple", "avocado", "banana", "cherry", "blueberry"] groups = {} for w in words: groups.setdefault(w[0], []).append(w) print(groups) - IntermediateDictionaries & sets
46. Set operations
For {1,2,3,4} and {3,4,5}, print the union, the intersection and what only the first set has.
Hint: Operators |, & and -.
a = {1, 2, 3, 4} b = {3, 4, 5}Show solution
a = {1, 2, 3, 4} b = {3, 4, 5} print(a | b) print(a & b) print(a - b) - IntermediateDictionaries & sets
47. Highest scorer
From {"Ada": 88, "Raj": 94, "Mia": 91}, print the name with the highest score.
Hint: max(scores, key=scores.get).
scores = {"Ada": 88, "Raj": 94, "Mia": 91}Show solution
scores = {"Ada": 88, "Raj": 94, "Mia": 91} print(max(scores, key=scores.get)) - AdvancedDictionaries & sets
48. Merge and total two carts
Merge {"pen": 2, "book": 1} and {"pen": 3, "bag": 1} so shared items add up.
Hint: Loop over the second dict and add to a copy of the first.
a = {"pen": 2, "book": 1} b = {"pen": 3, "bag": 1}Show solution
a = {"pen": 2, "book": 1} b = {"pen": 3, "bag": 1} merged = dict(a) for k, v in b.items(): merged[k] = merged.get(k, 0) + v print(merged) - BeginnerFunctions
49. Write your first function
Define square(n) that returns n squared and print square(9).
Hint: def name(arg): then return.
def square(n): passShow solution
def square(n): return n * n print(square(9)) - BeginnerFunctions
50. Default arguments
Write greet(name, greeting="Hello") and call it both with and without a greeting.
Hint: Defaults come after required parameters.
def greet(name, greeting="Hello"): passShow solution
def greet(name, greeting="Hello"): return f"{greeting}, {name}!" print(greet("Ada")) print(greet("Raj", "Namaste")) - IntermediateFunctions
51. Average of any many numbers
Write average(*nums) that returns 0 for no arguments and the mean otherwise.
Hint: *nums collects arguments into a tuple.
def average(*nums): passShow solution
def average(*nums): if not nums: return 0 return sum(nums) / len(nums) print(average(4, 8, 15)) print(average()) - IntermediateFunctions
52. Recursive factorial
Write a recursive factorial and print factorial(6).
Hint: Base case: factorial(0) is 1.
def factorial(n): passShow solution
def factorial(n): if n <= 1: return 1 return n * factorial(n - 1) print(factorial(6)) - AdvancedFunctions
53. Apply a function to a list
Write apply_all(fn, items) that returns a new list with fn applied to each item; test it with a doubling lambda.
Hint: Functions are values you can pass around.
def apply_all(fn, items): passShow solution
def apply_all(fn, items): return [fn(x) for x in items] print(apply_all(lambda x: x * 2, [1, 2, 3])) - AdvancedFunctions
54. Cache expensive calls
Speed up a recursive fib() with caching and print fib(35).
Hint: functools.lru_cache is a one-line decorator.
from functools import lru_cacheShow solution
from functools import lru_cache @lru_cache(maxsize=None) def fib(n): return n if n < 2 else fib(n - 1) + fib(n - 2) print(fib(35)) - BeginnerFiles & errors
55. Handle a bad number
Try to convert "12a" to an integer and print a friendly message instead of crashing.
Hint: except ValueError catches the failure.
raw = "12a"Show solution
raw = "12a" try: print(int(raw)) except ValueError: print("That is not a whole number") - BeginnerFiles & errors
56. Guard against divide by zero
Write safe_divide(a, b) that returns None when b is 0.
Hint: Catch ZeroDivisionError or check b first.
def safe_divide(a, b): passShow solution
def safe_divide(a, b): try: return a / b except ZeroDivisionError: return None print(safe_divide(10, 2)) print(safe_divide(10, 0)) - IntermediateFiles & errors
57. Raise your own error
Write set_age(n) that raises ValueError for negative ages, and catch it.
Hint: raise ValueError("message").
def set_age(n): passShow solution
def set_age(n): if n < 0: raise ValueError("age cannot be negative") return n try: set_age(-3) except ValueError as err: print("Error:", err) - IntermediateFiles & errors
58. Write then read a file
Write three lines to notes.txt, then read them back and print them.
Hint: Use with open(...) so the file closes itself.
Show solution
with open("notes.txt", "w") as f: f.write("one\ntwo\nthree\n") with open("notes.txt") as f: for line in f: print(line.strip()) - AdvancedFiles & errors
59. Always clean up
Show that a finally block runs even when the try block raises.
Hint: try / except / finally.
Show solution
try: 1 / 0 except ZeroDivisionError: print("caught it") finally: print("cleanup always runs") - BeginnerClasses
60. A Student class
Create a Student class with name and marks, and a describe() method that prints both.
Hint: __init__(self, ...) stores the values on self.
class Student: passShow solution
class Student: def __init__(self, name, marks): self.name = name self.marks = marks def describe(self): print(f"{self.name} scored {self.marks}") Student("Ada", 92).describe() - IntermediateClasses
61. Readable objects
Give a Book class a __str__ so printing it shows "Title by Author".
Hint: __str__ must return a string.
class Book: passShow solution
class Book: def __init__(self, title, author): self.title = title self.author = author def __str__(self): return f"{self.title} by {self.author}" print(Book("Clean Code", "Robert Martin")) - IntermediateClasses
62. Inheritance
Make Dog and Cat subclasses of Animal, each with its own speak().
Hint: class Dog(Animal): then override the method.
class Animal: def speak(self): return "..."Show solution
class Animal: def speak(self): return "..." class Dog(Animal): def speak(self): return "Woof" class Cat(Animal): def speak(self): return "Meow" for a in (Dog(), Cat()): print(a.speak()) - AdvancedClasses
63. Computed property
Give a Rectangle class an area property that is calculated, not stored.
Hint: Decorate the method with @property.
class Rectangle: passShow solution
class Rectangle: def __init__(self, w, h): self.w = w self.h = h @property def area(self): return self.w * self.h print(Rectangle(4, 6).area) - AdvancedClasses
64. Dataclass shortcut
Use @dataclass to build a Point with x and y, and print an instance.
Hint: from dataclasses import dataclass.
from dataclasses import dataclassShow solution
from dataclasses import dataclass @dataclass class Point: x: int y: int print(Point(3, 4)) - BeginnerAlgorithms
65. Linear search
Find the index of 30 in [5, 12, 30, 47] without using .index().
Hint: enumerate() gives index and value together.
nums = [5, 12, 30, 47] target = 30Show solution
nums = [5, 12, 30, 47] target = 30 for i, n in enumerate(nums): if n == target: print(i) break - IntermediateAlgorithms
66. Bubble sort
Sort [5, 1, 4, 2, 8] with bubble sort (no sorted()).
Hint: Repeatedly swap neighbours that are out of order.
nums = [5, 1, 4, 2, 8]Show solution
nums = [5, 1, 4, 2, 8] for i in range(len(nums)): for j in range(len(nums) - i - 1): if nums[j] > nums[j + 1]: nums[j], nums[j + 1] = nums[j + 1], nums[j] print(nums) - AdvancedAlgorithms
67. Binary search
Find 23 in a sorted list using binary search and print its index.
Hint: Halve the search window each turn with low, high and mid.
nums = [2, 5, 9, 13, 18, 23, 31] target = 23Show solution
nums = [2, 5, 9, 13, 18, 23, 31] target = 23 low, high = 0, len(nums) - 1 while low <= high: mid = (low + high) // 2 if nums[mid] == target: print(mid) break if nums[mid] < target: low = mid + 1 else: high = mid - 1 - IntermediateAlgorithms
68. Anagram detector
Decide whether "listen" and "silent" are anagrams.
Hint: sorted() on both strings gives comparable lists.
a, b = "listen", "silent"Show solution
a, b = "listen", "silent" print(sorted(a) == sorted(b)) - IntermediateAlgorithms
69. Second largest number
Find the second largest value in [10, 45, 45, 32, 7] (45 counts once).
Hint: Deduplicate with a set, then sort.
nums = [10, 45, 45, 32, 7]Show solution
nums = [10, 45, 45, 32, 7] print(sorted(set(nums))[-2]) - AdvancedAlgorithms
70. Two-sum pairs
Find the two numbers in [2, 7, 11, 15] that add to 18 and print them.
Hint: Store what you have seen in a set and look for target - n.
nums = [2, 7, 11, 15] target = 18Show solution
nums = [2, 7, 11, 15] target = 18 seen = set() for n in nums: if target - n in seen: print(target - n, n) break seen.add(n) - AdvancedAlgorithms
71. Word frequency report
Print the three most common words in a paragraph, ignoring case and punctuation.
Hint: Strip punctuation, lowercase, split, then use Counter.
from collections import CounterShow solution
from collections import Counter import string text = "Code, code and more code. Practice makes code readable." clean = text.lower().translate(str.maketrans("", "", string.punctuation)) for word, n in Counter(clean.split()).most_common(3): print(word, n)
What to do next
If a whole topic feels shaky, go back to that chapter in the 17-chapter Python course and re-read it, then return here. When the advanced problems feel routine, take the final Python quiz and claim your certificate, or open the Python online compiler and build something of your own.