How do you define a function in Python?
Use the `def` statement followed by a name and parentheses; the indented body contains the function’s statements. Defining it does not execute the body.
Study 4 Functions and Scope with 12 free online flashcards. Review key terms, definitions, and concepts with this interactive flashcard deck.
How do you define a function in Python?
Use the `def` statement followed by a name and parentheses; the indented body contains the function’s statements. Defining it does not execute the body.
How do you call a Python function?
Write the function name followed by parentheses, such as `greet()`. The parentheses perform the call; the name alone refers to the function object.
What is the difference between a parameter and an argument?
A parameter is a variable in the function definition; an argument is the value supplied by the caller. In `greet_person("Maya")`, `name` is the parameter and `"Maya"` is the argument.
How do positional and keyword arguments differ?
Positional arguments match parameters by order. Keyword arguments name the target parameter, making the call more explicit and allowing arguments to be supplied in a different order.
When are default parameter values used?
A default value is used when the caller omits that argument. Python evaluates the default when the function is defined, so avoid mutable defaults such as lists; use `None` when a fresh mutable object is needed.
How does `return` differ from `print`?
`return` sends a value to the caller, so it can be assigned, used in an expression, or passed elsewhere. `print` only displays a value and does not provide it as the function result.
What does a function return without an explicit value?
If execution reaches the end of a function without a `return` statement, the function returns `None`. A bare `return` also returns `None`.
How does Python return multiple values?
Python packages multiple returned values into a tuple. For example, `return min(numbers), max(numbers)` can be unpacked with `low, high = min_and_max(numbers)`.
What does the LEGB rule describe?
Python generally resolves names in LEGB order: Local, Enclosing, Global, then Built-in. It searches each applicable scope in that sequence.
What scope does an assignment inside a function use by default?
An assignment inside a function creates a local name by default, even when a global variable has the same name. The local assignment does not change the global variable.
When is the `global` statement needed?
Use `global` inside a function to rebind a module-level variable. Because global state can make code harder to test and reason about, use it sparingly.
What does `nonlocal` do?
Use `nonlocal` in a nested function to rebind a name from an enclosing function’s scope. Without it, an assignment such as `count += 1` is treated as local to the nested function.