Zum Inhalt

Python-Spickzettel

Eine technische Referenz für die schnelle Suche nach der Kernsyntax von Python, integrierten Datentypen, Kontrollflussoperationen und Dateimanipulation.


1. Kerndatenstrukturen und native Methoden

Listen (geordnete, veränderliche Sammlungen)

# Initialization
items = ["flask", "pandas", "pytest"]

# Core Operations
items.append("selenium")       # Adds to end -> ['flask', 'pandas', 'pytest', 'selenium']
items.insert(1, "tkinter")     # Inserts at index -> ['flask', 'tkinter', 'pandas', 'pytest', 'selenium']
items.remove("pandas")         # Removes first occurrence by value
popped_val = items.pop(0)      # Removes and returns item by index (default: last element)

# Slicing: list[start:stop:step]
sub_set = items[0:2]           # Elements from index 0 up to (but excluding) 2
reversed_items = items[::-1]   # Reverses the list cleanly

Wörterbücher (Schlüsselwert-Hash-Maps)

# Initialization
developer = {"name": "Marwa", "role": "Data Engineer", "active": True}

# Core Operations
developer["language"] = "Python"               # Adds or updates key
role = developer.get("role", "Default Role")  # Safe lookup; prevents KeyError if missing

# Iteration Patterns
for key in developer.keys():                  # Loops through keys
    print(key)

for key, value in developer.items():          # Loops through both keys and values
    print(f"{key}: {value}")

Tupel (geordnete, unveränderliche Sequenzen)

# Initialization (Fixed memory footprints)
coordinates = (10.0, 20.5)
system_config = ("localhost", 8080)

# Unpacking Data Structures
host, port = system_config                     # host = "localhost", port = 8080

Sets (ungeordnete, einzigartige Sammlungen)

# Initialization
tags_a = {"backend", "data_science", "testing"}
tags_b = {"testing", "automation", "frontend"}

# Core Operations & Venn Matrix Math
tags_a.add("scraping")
common_tags = tags_a.intersection(tags_b)      # -> {'testing'}
all_tags = tags_a.union(tags_b)                # Combines collections and drops duplicates

2. Kontrollfluss- und Iterations-Frameworks

Bedingte logische Anweisungen

execution_mode = "production"

if execution_mode == "development":
    log_level = "DEBUG"
elif execution_mode == "staging":
    log_level = "INFO"
else:
    log_level = "CRITICAL"

Schleifen und Verständnis

# Standard For Loop with Range Bounds
for index in range(0, 5):                      # Generates numbers 0 through 4
    print(index)

# List Comprehension (Eager Memory Array Allocation)
squares = [x**2 for x in range(10) if x % 2 == 0]

# Dictionary Comprehension
matrix_map = {f"square_{x}": x**2 for x in range(5)}

3. Funktionsblöcke und Bereichslayouts

Benutzerdefinierte Funktionspläne

# Function with default keyword arguments and structural Type Hints
def process_data_payload(payload: list, strict_mode: bool = False) -> dict:
    """
    Ingests structural lists and validates operational records.
    """
    if not payload:
        return {"status": "empty"}

    processed_count = len(payload)
    return {"status": "success", "count": processed_count}

Lambda-Ausdrücke (anonyme einzeilige Funktionen)

# Syntax -> lambda arguments: expression
multiply_coords = lambda x, y: x * y
print(multiply_coords(5, 10))                  # -> 50

# Commonly used as a parsing key modifier sorting collections
raw_pairs = [(1, "pandas"), (2, "flask"), (3, "asyncio")]
raw_pairs.sort(key=lambda item: item[1])       # Sorts list alphabetically by the string value

4. Erweiterte Funktionsargumente (*args und kwargs)

*args (Variable Positionsargumente)

def calculate_sum(*args: float) -> float:
    # args is treated internally as a tuple -> (10, 20, 30)
    total = 0
    for number in args:
        total += number
    return total

# Usage
print(calculate_sum(10, 20, 30))               # -> 60.0

kwargs (Variable Schlüsselwortargumente)

def configure_environment(**kwargs: str) -> None:
    # kwargs is treated internally as a dict -> {"mode": "prod", "db": "postgres"}
    mode = kwargs.get("mode", "development")
    database = kwargs.get("db", "sqlite3")
    print(f"Running in {mode} split using {database}.")

# Usage
configure_environment(mode="production", db="postgresql", cache="redis")

Kombiniertes Signaturmuster

def master_pipeline_engine(target_id, *args, default_timeout=30, **kwargs):
    print(f"Target: {target_id}")              # Standard input
    print(f"Positional args: {args}")          # Tuple matching extra values
    print(f"Timeout limit: {default_timeout}")  # Keyword default parameter
    print(f"Metadata maps: {kwargs}")          # Dictionary capturing extra keys

5. Objektorientierte Programmierung (OOP-Klassen)

Blaupause für die Kernklassenstruktur

class SoftwareDeveloper:
    # Class Attribute (Shared universally across all instances)
    ecosystem = "Python"

    # Constructor method (__init__) initializes unique instance data states
    def __init__(self, name: str, role: str, experience_years: int):
        self.name = name                       # Instance Attribute
        self.role = role                       # Instance Attribute
        self.experience = experience_years     # Instance Attribute

    # Instance Method (Requires 'self' parameter token to read instance state)
    def promote(self, new_role: str) -> None:
        print(f"Upgrading {self.name} from {self.role} to {new_role}.")
        self.role = new_role

    # Special Dunder Method for readable string presentation
    def __str__(self) -> str:
        return f"Developer: {self.name} | Role: {self.role}"

# Usage & Instantiation
dev_instance = SoftwareDeveloper("Marwa", "Data Analyst", 3)
dev_instance.promote("Data Scientist")         # Executes instance method mutation
print(dev_instance)                            # Invokes __str__ -> Developer: Marwa | Role: Data Scientist

Vererbung und Basisüberschreibung

class AutomationEngineer(SoftwareDeveloper):
    """
    Child class inheriting core variables from parent class SoftwareDeveloper.
    """
    def __init__(self, name: str, experience_years: int, test_framework: str):
        # super().__init__() passes requirements back up to parent class initializer
        super().__init__(name=name, role="QA Engineer", experience_years=experience_years)
        self.framework = test_framework        # Unique extension attribute

    # Overriding: Modifies parent method behavior to perform specific logic
    def promote(self, new_role: str) -> None:
        print(f"Overriding check: {self.name} is transitioning to Senior {self.framework} Architect.")
        self.role = f"Senior {new_role}"

6. E/A-Operationen des nativen Dateisystems

# Safe Content Writing Execution Context
with open("output_report.txt", mode="w", encoding="utf-8") as file:
    file.write("System execution completed successfully.\n")
    file.write("Data pipeline flushed onto physical partition.")

# Safe Content Reading Execution Context
with open("output_report.txt", mode="r", encoding="utf-8") as file:
    content = file.read()                      # Reads whole file into one string block

# Reading Large Files line-by-line efficiently (Memory Optimization)
with open("massive_dataset.csv", mode="r", encoding="utf-8") as data_stream:
    for row in data_stream:
        print(row.strip())                     # Processes individual lines without loading entire file to RAM

7. Fehlererkennung und Ausnahmeabfangen

Try-Except-Blöcke

def safe_divide(numerator: float, denominator: float) -> float:
    try:
        result = numerator / denominator
    except ZeroDivisionError as zero_error:
        print(f"Mathematical Bound Exception: {zero_error}")
        result = 0.0
    except TypeError as type_error:
        print(f"Data Schema Exception: {type_error}")
        result = 0.0
    else:
        print("Division executed with no structural exceptions caught.")
    finally:
        print("Calculation block closed down memory operations.")

    return result