Python exercises with solutions
Solve in editor
Write your solution right in the browser and have it checked automatically.
Open exercises with editor1. Even numbers Beginner
Print all even numbers from 1 to 10 – each on its own line.
Expected output: 2 ⏎ 4 ⏎ 6 ⏎ 8 ⏎ 10
Note
range(2, 11, 2) steps in twos. Or check with % 2 == 0.
Show sample solution
for i in range(2, 11, 2):
print(i)2. FizzBuzz (1–15) Beginner
Print the numbers 1 to 15. For multiples of 3 print Fizz instead, for multiples of 5 print Buzz, and for both print FizzBuzz.
Expected output: 1 ⏎ 2 ⏎ Fizz ⏎ 4 ⏎ Buzz ⏎ Fizz ⏎ 7 ⏎ 8 ⏎ Fizz ⏎ Buzz ⏎ 11 ⏎ Fizz ⏎ 13 ⏎ 14 ⏎ FizzBuzz
Note
Check the "divisible by 15" case first.
Show sample solution
for i in range(1, 16):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)3. Reverse a word Beginner
Reverse the string "Python" and print it.
Expected output: nohtyP
Note
Slicing with a negative step: [::-1].
Show sample solution
wort = "Python"
print(wort[::-1])4. Sum of squares Beginner
Calculate the sum of the squares of the numbers 1 to 10 and print it.
Expected output: 385
Note
sum() and a generator expression: x**2 for x in range(1, 11).
Show sample solution
print(sum(x**2 for x in range(1, 11)))5. Palindrome function Intermediate
Write a function ist_palindrom(text) that returns True if the text reads the same forwards and backwards (ignoring case). Print ist_palindrom("Anna") and ist_palindrom("Python").
Expected output: True ⏎ False
Note
First convert with .lower() and compare with the reversed version.
Show sample solution
def ist_palindrom(text):
t = text.lower()
return t == t[::-1]
print(ist_palindrom("Anna"))
print(ist_palindrom("Python"))6. Most frequent word Intermediate
Find the most frequent word in "a b a c b a" and print it.
Expected output: a
Note
collections.Counter(...).most_common(1) returns a list containing one tuple.
Show sample solution
from collections import Counter
text = "a b a c b a"
print(Counter(text.split()).most_common(1)[0][0])7. Primes up to 30 Intermediate
Print all prime numbers up to 30 on one line, separated by spaces.
Expected output: 2 3 5 7 11 13 17 19 23 29
Note
A number n is prime if it is not divisible by any number from 2 to n-1. all(...) helps.
Show sample solution
primes = [n for n in range(2, 31) if all(n % d for d in range(2, n))]
print(*primes)