Lernziele dieses Kapitels
- You define functions with def and understand return
- You use parameters, default values, and type hints
- You use *args and **kwargs for flexible arguments
- You build PyBuddy's helper functions
Defining Functions
With def you encapsulate code into reusable building blocks. A function is like a recipe: you put in ingredients (parameters) and get a result (return) back.
Pro Tip
Good functions do one thing and do it well. If your function is longer than 20 lines, consider splitting it up.
Parameters and Default Values
Functions can have optional parameters with default values. You can also pass named arguments — then the order doesn't matter.
*args and **kwargs
Sometimes you don't know in advance how many arguments a function will get. *args collects any number of positional arguments as a tuple, **kwargs collects named arguments as a dictionary.
Lambda Functions
Lambda functions are small, anonymous functions in one line. They are perfect for short operations that you don't want to define separately with def.
Scope and Docstrings
Variables inside a function are local — they only exist there. Variables outside are global. Docstrings (three quotation marks directly under def) document your function.
Warm-Up: Temperature Converter
Write two functions: c_to_f(c) and c_to_k(c). Call them with a user input.
Hinweis:
Challenge: Login Validator
Create a function ist_gueltig(benutzer, passwort) that checks: username at least 3 characters, password at least 8 characters. Return True or False.
Hinweis:
PyBuddy Checkpoint: Formatting Helpers
PyBuddy gets helper functions for text formatting and validation that will be used throughout the entire project later.
Hinweis:
In Super Mario Bros. there is a function springen() that checks: Is Mario on the ground? Then set velocity Y to -15. Every jump in the game is a function call with parameters — exactly like what you're programming now!
Zusammenfassung
- def name(): → Define a function
- Parameters + default values for flexibility
- *args, **kwargs for arbitrary arguments
- Lambda for short anonymous functions
- Docstrings document your code