Python Examples

These Python examples bring together everything from the tutorial: variables, loops, functions, collections and classes. Read each program, predict the output, then click "Try it Yourself" and change it. Modifying working code is one of the fastest ways to learn.

FizzBuzz

Print numbers from 1 to 15, but print Fizz for multiples of 3, Buzz for multiples of 5, and FizzBuzz for multiples of both. It practises loops, the % operator and if/elif.

for n in range(1, 16):
    if n % 15 == 0:
        print("FizzBuzz")
    elif n % 3 == 0:
        print("Fizz")
    elif n % 5 == 0:
        print("Buzz")
    else:
        print(n)
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Prime Numbers

A prime number is only divisible by 1 and itself. Checking divisors up to the square root is enough, which keeps the function fast.

def is_prime(n):
    if n < 2:
        return False
    for d in range(2, int(n ** 0.5) + 1):
        if n % d == 0:
            return False
    return True

print([n for n in range(1, 40) if is_prime(n)])
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]

Palindrome Checker

A palindrome reads the same backwards. We clean the text first, keeping only letters and digits in lowercase.

def is_palindrome(text):
    clean = "".join(ch.lower() for ch in text if ch.isalnum())
    return clean == clean[::-1]

for phrase in ["Racecar", "Never odd or even", "Python"]:
    print(phrase, "->", is_palindrome(phrase))
Racecar -> True
Never odd or even -> True
Python -> False

Word Frequency Counter

Count how often each word appears in a sentence, using a dictionary and sorting by count.

text = "the cat and the dog and the bird"
counts = {}

for word in text.split():
    counts[word] = counts.get(word, 0) + 1

for word, n in sorted(counts.items(), key=lambda kv: kv[1], reverse=True)[:3]:
    print(word, n)
the 3
and 2
cat 1

Shopping Cart Class

A small class that stores items in a dictionary and calculates the total with tax.

class Cart:
    def __init__(self):
        self.items = {}

    def add(self, name, price, qty=1):
        old_qty = self.items.get(name, (price, 0))[1]
        self.items[name] = (price, old_qty + qty)

    def total(self, tax=0.1):
        subtotal = sum(p * q for p, q in self.items.values())
        return round(subtotal * (1 + tax), 2)

cart = Cart()
cart.add("Basmati Rice", 12.5, 2)
cart.add("Green Tea", 6.0)
cart.add("Green Tea", 6.0)
print(cart.items)
print("Total:", cart.total())
{'Basmati Rice': (12.5, 2), 'Green Tea': (6.0, 2)}
Total: 40.7

Grade Report

Combine a list of dictionaries, a function, f-string alignment and summary statistics into a tidy report.

students = [
    {"name": "Ali", "marks": [78, 85, 90]},
    {"name": "Sara", "marks": [92, 88, 95]},
    {"name": "John", "marks": [55, 62, 48]},
]

def average(marks):
    return sum(marks) / len(marks)

for s in students:
    avg = average(s["marks"])
    result = "PASS" if avg >= 60 else "FAIL"
    print(f"{s['name']:<6}{avg:6.1f}  {result}")

best = max(students, key=lambda s: average(s["marks"]))
print("Top student:", best["name"])
Ali     84.3  PASS
Sara    91.7  PASS
John    55.0  FAIL
Top student: Sara

Ideas to Practise Next

  • Change FizzBuzz to use different numbers and words
  • Write a function that returns the n-th Fibonacci number
  • Add a remove() method to the Cart class
  • Build a number-guessing game on your own computer, where input() is available
  • Read a CSV file with the csv module and print a summary

Frequently asked questions

What are good Python practice programs for beginners?

Classic exercises include FizzBuzz, prime checks, palindromes, temperature converters, word counters and small classes like a bank account or shopping cart. They cover loops, conditions, functions and data structures.

What should I learn after the Python basics?

Pick an area and build projects: Flask or Django for web apps, pandas for data analysis, or automation scripts for everyday tasks. Learning to use Git and virtual environments helps in every area.

How can I get better at Python quickly?

Write code every day, even small scripts. Change the examples you read, solve coding challenges, and read other people's code to pick up idiomatic patterns.