iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Examples

A curated set of small, realistic Python programs you can paste into the editor and adapt.

FizzBuzz, the Pythonic way

PYTHON
for n in range(1, 21):
    out = ('Fizz' if n % 3 == 0 else '') + ('Buzz' if n % 5 == 0 else '')
    print(out or n)

Word frequency

PYTHON
from collections import Counter
text = 'the quick brown fox jumps over the lazy dog the fox the fox'
print(Counter(text.split()).most_common(3))

Read JSON, transform, write CSV

PYTHON
import json, csv

data = json.loads('[{"name":"Ada","age":36},{"name":"Linus","age":42}]')
with open('out.csv', 'w', newline='') as f:
    w = csv.DictWriter(f, fieldnames=['name', 'age'])
    w.writeheader()
    w.writerows(data)

Mini class — bank account

PYTHON
class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance
    def deposit(self, amount):
        if amount <= 0:
            raise ValueError('amount must be positive')
        self.balance += amount
    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError('insufficient funds')
        self.balance -= amount

a = Account('Ada', 100)
a.deposit(50)
a.withdraw(30)
print(a.owner, a.balance)

Simple HTTP GET (in the real Python)

PYTHON
import urllib.request, json
with urllib.request.urlopen('https://httpbin.org/json') as r:
    print(json.loads(r.read())['slideshow']['title'])

Generator: Fibonacci

PYTHON
def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

from itertools import islice
print(list(islice(fib(), 10)))
Tip: Once you spot a useful one-liner, save it as a code snippet in your editor. Two years in, you'll have a personal toolbox.

Example

Example
# A small grab-bag of patterns:
total = sum(n * n for n in range(1, 11))
print('sum of squares 1..10 =', total)

from collections import Counter
print(Counter('mississippi').most_common(2))
Try it Yourself »

Exercise

collections class for counting hashables.

from collections import

Test yourself

Q1. Word frequency one-liner uses…
Q2. Fibonacci is naturally a…
Q3. Reach for itertools.islice when…

Discussion

Loading…