PyPython

Python: More snippets – code examples

Contents

if / elif / else

Control flow#if#conditionCompare in all languages
Use case: React differently, e.g. calculate grades or price tiers.
punkte = 73
if punkte >= 90:
    print("very good")
elif punkte >= 70:
    print("good")
else:
    print("needs improvement")

Indentation forms the block; elif stands for "else if".

for loop

Control flow#for#loop#rangeCompare in all languages
Use case: Process every element of a list or repeat n times.
for i in range(3):
    print("Round", i)

for frucht in ["Apple", "Pear"]:
    print(frucht)

range(3) yields 0, 1, 2; the second loop runs directly over the list.

Function with default value

Functions#def#return#functionCompare in all languages
Use case: Bundle recurring logic, e.g. greeting texts or calculations.
def begruesse(name, gruss="Hello"):
    return f"{gruss}, {name}!"

print(begruesse("Ada"))
print(begruesse("Linus", gruss="Hi"))

Parameters with a default value are optional; named arguments make calls readable.

Class with inheritance

OOP#class#oop#inheritanceCompare in all languages
Use case: Bundle data and behavior, e.g. users, products, game characters.
class Tier:
    def __init__(self, name):
        self.name = name
    def sprich(self):
        return f"{self.name} makes a sound"

class Hund(Tier):
    def sprich(self):
        return f"{self.name} says Woof!"

print(Hund("Rex").sprich())

Hund inherits from Tier and overrides sprich.

Dataclass

OOP#dataclass#class
Use case: Pure data objects without boilerplate, e.g. configurations or DTOs.
from dataclasses import dataclass, field

@dataclass
class Produkt:
    name: str
    preis: float
    tags: list = field(default_factory=list)

p = Produkt("Coffee", 4.5)
p.tags.append("hot")
print(p)
print(p == Produkt("Coffee", 4.5, ["hot"]))

Generates __init__, __repr__ and __eq__ automatically.

try / except / finally

Error handling#try#except#exceptionCompare in all languages
Use case: Guard user input or network access without the program crashing.
try:
    zahl = int("abc")
except ValueError as e:
    print("Invalid:", e)
finally:
    print("Cleaning up")

finally always runs – ideal for closing resources.

Reading and writing a file

Files#open#file#withCompare in all languages
Use case: Save and load logs, configurations or text data.
with open("notizen.txt", "w", encoding="utf-8") as f:
    f.write("Line 1\nLine 2\n")

with open("notizen.txt", encoding="utf-8") as f:
    for zeile in f:
        print(zeile.strip())

with closes the file automatically, even on errors.

Reading and writing JSON

Files#json#serialization
Use case: Exchange data with web APIs or other programs.
import json

daten = {"name": "Ada", "sprachen": ["Python", "C"]}
text = json.dumps(daten, indent=2, ensure_ascii=False)
print(text)
zurueck = json.loads(text)
print(zurueck["sprachen"][0])

dumps converts Python to a JSON string, loads converts it back.

Counting words

Strings#counter#split#text
Use case: Text analysis, e.g. most frequent words in a document.
from collections import Counter

text = "this is a test this is good"
zaehler = Counter(text.split())
print(zaehler.most_common(2))   # [('this', 2), ('is', 2)]

Counter is a special dictionary for counting.

Regular expression

Strings#regex#re#pattern
Use case: Find email addresses, phone numbers or patterns in text.
import re

text = "Contact: ada@example.com, bob@test.org"
mails = re.findall(r"[\w.]+@[\w.]+\.\w+", text)
print(mails)
print(re.sub(r"\d+", "#", "Phone 12345"))

findall returns all matches, sub replaces patterns.

HTTP request (requests)

Networking#http#requests#api
Use case: Fetch data from a web API.
import requests

antwort = requests.get("https://api.github.com/repos/python/cpython", timeout=10)
antwort.raise_for_status()
daten = antwort.json()
print(daten["full_name"], daten["stargazers_count"])

Requires pip install requests. raise_for_status raises an exception on HTTP errors.

Command-line arguments

Tools#cli#argparse
Use case: Build your own CLI tools with options.
import argparse

parser = argparse.ArgumentParser(description="Greets someone")
parser.add_argument("name")
parser.add_argument("--laut", action="store_true")
args = parser.parse_args()

text = f"Hello {args.name}"
print(text.upper() if args.laut else text)

Call it e.g. with python tool.py Ada --laut. --help is generated automatically.