Python examples · ready to run
Python examples — eight short programs explained
The fastest way to get better at Python is to write small programs. Here are eight classic exercises: the code, what it prints and what each one teaches you.
1. Even numbers
Practises loops and the remainder operator.
for number in range(1, 11):
if number % 2 == 0:
print(number, "is even")
2 is even
4 is even
6 is even
8 is even
10 is even
2. Times table
A loop inside a loop — the basis of every table and grid.
for row in range(1, 4):
for column in range(1, 4):
print(row * column, end=" ")
print()
1 2 3
2 4 6
3 6 9
3. Guessing game
Your first tiny game: the program keeps a secret number and reacts to guesses.
secret = 7
while True:
guess = int(input("Guess the number: "))
if guess == secret:
print("You got it!")
break
print("Try again.")
Guess the number: 3
Try again.
Guess the number: 7
You got it!
4. Average of grades
Lists, sum and division — the basis of working with data.
grades = [1, 2, 1, 3, 2]
average = sum(grades) / len(grades)
print("Average:", round(average, 2))
Average: 1.8
5. FizzBuzz
The classic interview exercise. It trains conditions and the order you test them in.
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)
1
2
Fizz
4
Buzz
...
FizzBuzz
6. Palindrome
String handling and reversing text with a slice.
word = input("Enter a word: ").lower()
if word == word[::-1]:
print("It is a palindrome.")
else:
print("Not a palindrome.")
Enter a word: kayak
It is a palindrome.
7. Counting words
Splitting text and using a dictionary — this is how you count anything.
sentence = "python is fun and python is free"
counts = {}
for word in sentence.split():
counts[word] = counts.get(word, 0) + 1
print(counts["python"], "x python")
2 x python
8. Calculator
Input, conditions and one error handled properly.
a = float(input("First number: "))
b = float(input("Second number: "))
operation = input("Operation (+ - * /): ")
if operation == "+":
print(a + b)
elif operation == "-":
print(a - b)
elif operation == "*":
print(a * b)
elif operation == "/" and b != 0:
print(a / b)
else:
print("I can't compute that.")
First number: 8
Second number: 2
Operation (+ - * /): /
4.0
Frequently asked questions
Where can I run these examples?
In the course itself — it has a playground that runs your code in the browser, with no install.
Why do I get an IndentationError?
Python cares about indentation. Lines inside a condition or a loop must be indented by four spaces.
Are there harder examples?
Yes. The course has 400 lessons, from your first print to algorithms, tests and ten bigger projects.
Read next
Write your first program today
Creating an account takes a minute. Your first lesson takes five.
Start for free