Funktionen & Generatoren
Python Syntax Guide
Funktionsdefinitionen und Generatorfunktionen in Python
Funktionen & Generatoren
Funktionsdefinitionen und Generatorfunktionen in Python
# Function definition
def greet(name, greeting="Hello"):
"""Function with docstring and default parameter"""
return f"{greeting}, {name}!"
# Function with *args and **kwargs
def flexible_function(*args, **kwargs):
print("Positional args:", args)
print("Keyword args:", kwargs)
flexible_function(1, 2, 3, name="John", age=25)
# Lambda functions
square = lambda x: x ** 2
print(square(5)) # 25
# Generator function
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
for num in fibonacci(10):
print(num, end=" ") # 0 1 1 2 3 5 8 13 21 34
# Generator expression
squares_gen = (x**2 for x in range(10))
print(list(squares_gen)) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Decorators
def timer(func):
def wrapper(*args, **kwargs):
import time
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.2f} seconds")
return result
return wrapper
@timer
def slow_function():
import time
time.sleep(1)
return "Done"
slow_function()
Explanation
Common Use Cases
- Code-Wiederverwendbarkeit
- Speichereffiziente Iteration
- Funktionsmodifikation
- Leistungsüberwachung
Related Python Syntax
Variables & Data Types
Python variables and data types
Control Flow
Conditional statements and loops in Python
Classes & OOP
Object-oriented programming with classes in Python
Modules & Packages
Importing and organizing code with modules and packages
Exception Handling
Error handling with try/except blocks in Python
Master Funktionen & Generatoren in Python
Understanding Funktionen & Generatoren is fundamental to writing clean and efficient Python code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.
Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using Funktionen & Generatoren effectively in your Python projects.
Key Takeaways
- Code-Wiederverwendbarkeit
- Speichereffiziente Iteration
- Funktionsmodifikation