Python exercises for beginners, solved and explained (runnable in your browser)
The most effective way to learn Python is not reading theory: it is solving small exercises and seeing the result immediately. Below are six progressive exercises, each with an explained solution, and you can run and edit them right on this page with "Try it".
Exercise 1 — Greet the user
Print a personalised greeting.
name = "Julia"
print("Hi, " + name + "! Welcome.")Strings are joined with +. Change the name and run it again.
Exercise 2 — Sum of two numbers
Add two numbers and show the result.
a = 8
b = 5
print("The sum is", a + b)print can take several comma-separated values: it prints them one after another with a space.
Exercise 3 — Even or odd
Say whether a number is even or odd.
number = 7
if number % 2 == 0:
print(number, "is even")
else:
print(number, "is odd")% is the remainder of a division: if the remainder mod 2 is zero, the number is even. It is one of the most used tricks ever.
Exercise 4 — Count from 1 to 5
Print every number from 1 to 5.
for i in range(1, 6):
print(i)range(1, 6) produces the numbers 1 to 5 (the right end is excluded). Change the 6 and see what happens.
Exercise 5 — Sum of the first 100 numbers
Add every number from 1 to 100.
total = 0
for i in range(1, 101):
total = total + i
print("The sum from 1 to 100 is", total)Here you accumulate: start at zero and add the current number each round. It is the basic pattern of almost any calculation.
Exercise 6 — Find the largest
Find the biggest number in a list.
numbers = [3, 9, 2, 15, 7]
biggest = numbers[0]
for n in numbers:
if n > biggest:
biggest = n
print("The largest is", biggest)Start with the first as the "reigning champion" and replace it whenever you find a bigger one. When this pattern feels natural, you have made a real leap.
What next?
If you enjoyed these, the Python path has hundreds more like them, from your first print to functions, dictionaries and OOP: short theory then immediate practice in the browser, with XP and streaks. The first chapters are free. Just want to experiment? The playground is open.