10 Python practice problems for beginners (with solutions)
12 min read
Reading about Python only gets you so far. You learn it by writing code, getting stuck and getting unstuck. These ten problems cover the basics every beginner needs: strings, loops, conditions, lists and dictionaries. They start easy and get a little harder.
For each one, try it yourself first. If you're stuck for more than ten minutes, open the hint. Then compare your answer with the solution, and read the note underneath: it's usually the part that teaches you the most.
1. Reverse a string
Write a function reverse(text) that returns the text backwards. reverse("hello") should return "olleh".
Show hintHint
A slice takes three numbers, text[start:stop:step]. What does a step of -1 do?
Show solutionSolution
def reverse(text):
return text[::-1]
print(reverse("hello"))Leaving out start and stop means “the whole string”, and a step of -1 walks it from the end. It's worth knowing because slicing works the same way on lists.
2. Count the vowels
Write count_vowels(text) that returns how many vowels are in the text, upper or lower case. count_vowels("Blackprint") returns 2.
Show hintHint
Loop over text.lower() and check if char in "aeiou".
Show solutionSolution
def count_vowels(text):
count = 0
for char in text.lower():
if char in "aeiou":
count += 1
return count
print(count_vowels("Blackprint"))Lower-casing once at the start means you don't need to check for "A" and "a" separately. in works on strings as well as lists.
3. FizzBuzz
Write fizzbuzz(n) that returns a list for the numbers 1 to n: "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for multiples of both, and the number as text otherwise. fizzbuzz(5) returns ["1", "2", "Fizz", "4", "Buzz"].
Show hintHint
Check the “both” case first.
Show solutionSolution
def fizzbuzz(n):
result = []
for i in range(1, n + 1):
if i % 15 == 0:
result.append("FizzBuzz")
elif i % 3 == 0:
result.append("Fizz")
elif i % 5 == 0:
result.append("Buzz")
else:
result.append(str(i))
return result
print(fizzbuzz(15))The classic mistake is checking % 3 first: then 15 stops at “Fizz” and never reaches “FizzBuzz”, because elif stops at the first true condition. Also note range(1, n + 1): range stops before its end value.
4. Find the largest number without max()
Write largest(numbers) that returns the biggest number in a list, without using the built-in max(). largest([3, 9, 2]) returns 9.
Show hintHint
Start with the first number as your best guess, then replace it whenever you find something bigger.
Show solutionSolution
def largest(numbers):
best = numbers[0]
for n in numbers[1:]:
if n > best:
best = n
return best
print(largest([3, 9, 2]))
print(largest([-5, -1, -8]))Many beginners start with best = 0. That breaks on a list of negative numbers: [-5, -1, -8] would return 0, which isn't even in the list. Starting from numbers[0] returns the correct -1.
5. Is it a palindrome?
Write is_palindrome(text) that returns True if the text reads the same backwards, ignoring case and spaces. is_palindrome("Never odd or even") returns True.
Show hintHint
Clean the text first, then reuse your answer to problem 1.
Show solutionSolution
def is_palindrome(text):
cleaned = text.lower().replace(" ", "")
return cleaned == cleaned[::-1]
print(is_palindrome("Never odd or even"))== already gives True or False, so there's no need for if ... return True else return False.
6. Turn minutes into hours and minutes
Write format_minutes(total) that turns a number of minutes into text like "2:05". format_minutes(125) returns "2:05".
Show hintHint
// gives whole hours and % gives the minutes left over.
Show solutionSolution
def format_minutes(total):
hours = total // 60
minutes = total % 60
return f"{hours}:{minutes:02}"
print(format_minutes(125))// is division that drops the remainder, and % is the remainder. The :02 in the f-string pads the minutes to two digits, so you get 2:05, not 2:5.
7. Turn a score into a letter grade
Write grade(score) that returns "A" for 90 and up, "B" for 80 to 89, "C" for 70 to 79, "D" for 60 to 69 and "F" below 60.
Show hintHint
Check from the top down.
Show solutionSolution
def grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
print(grade(95), grade(80), grade(42))Because each elif only runs when everything above it was false, you never need to write 80 <= score < 90.
8. Remove duplicates and keep the order
Write unique(items) that returns a new list without duplicates, keeping the first time each item appears. unique([3, 1, 3, 2, 1]) returns [3, 1, 2].
Show hintHint
Keep a set of the items you've already seen.
Show solutionSolution
def unique(items):
seen = set()
result = []
for item in items:
if item not in seen:
seen.add(item)
result.append(item)
return result
print(unique([3, 1, 3, 2, 1]))list(set(items)) also removes duplicates, but a set doesn't keep order, so the result can come back shuffled. A neat one-line alternative that does keep order: list(dict.fromkeys(items)).
9. Count how often each word appears
Write word_counts(text) that returns a dictionary of each word and how many times it appears. word_counts("the cat and the hat") returns {"the": 2, "cat": 1, "and": 1, "hat": 1}.
Show hintHint
counts.get(word, 0) returns the current count, or 0 if the word isn't there yet.
Show solutionSolution
def word_counts(text):
counts = {}
for word in text.lower().split():
counts[word] = counts.get(word, 0) + 1
return counts
print(word_counts("the cat and the hat"))This counting pattern comes up constantly. Python also has it built in: from collections import Counter, then Counter(text.lower().split()).
10. Find the second largest number
Write second_largest(numbers) that returns the second largest different number, or None if there isn't one. second_largest([5, 5, 3]) returns 3.
Show hintHint
Remove duplicates first.
Show solutionSolution
def second_largest(numbers):
distinct = sorted(set(numbers))
if len(distinct) < 2:
return None
return distinct[-2]
print(second_largest([5, 5, 3]))
print(second_largest([2, 2]))Duplicates are the trap. Without set(), sorted([5, 5, 3])[-2] is 5, not 3. And always think about the edge cases: what should happen with [2, 2] or an empty list?
What to practice next
If these felt comfortable, you're ready for problems that combine several ideas at once, like reading data from a file and summarizing it. If some felt hard, that's normal: redo them tomorrow without looking at the solutions.
Practice with feedback. Blackprint's Intro to Python has coding challenges in every module, with tests that check your code as you go and a built-in editor, so there's nothing to install. The first module is free. Start Intro to Python