How does a python function work? Flashcards

(5 cards)

1
Q

function summary

A

Python functions are the building blocks of code organization, often serving predefined tasks within modules and scripts.

They enable reusability, modularity, and encapsulation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Key Components of functions

A

Function Signature: Denoted by the def keyword, it includes the function name, parameters, and an optional return type.

Function Body: This section carries the core logic, often comprising conditional checks, loops, and method invocations.

Return Statement: The function’s output is determined by this statement. When None is specified, the function returns by default.

Local Variables: These variables are scoped to the function and are only accessible within it

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

function Execution Process

A

When a function is called:

  1. Stack Allocation: A stack frame, also known as an activation record, is created to manage the function’s execution. This frame contains details like the function’s parameters, local variables, and instruction pointer.
  2. Parameter Binding: The arguments passed during the function call are bound to the respective parameters defined in the function header.
  3. Function Execution: Control is transferred to the function body. The statements in the body are executed in a sequential manner until the function hits a return statement or the end of the function body.
  4. Return: If a return statement is encountered, the function evaluates the expression following the return and hands the value back to the caller. The stack frame of the function is then popped from the call stack.
  5. Post Execution: If there’s no return statement, or if the function ends without evaluating any return statement, None is implicitly returned.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

function Local Variable Scope

A

Function Parameters: These are a precursor to local variables and are instantiated with the values passed during function invocation.

Local Variables: Created using an assignment statement inside the function and cease to exist when the function execution ends.

Nested Scopes: In functions within functions (closures), non-local variables - those defined in the enclosing function - are accessible but not modifiable by the inner function, without using the nonlocal keyword

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is Global Visibility?

A

Functions offer a level of encapsulation, potentially reducing side effects by ensuring that data and variables are managed within a controlled environment. Such containment can help enhance the robustness and predictability of a codebase. As a best practice, minimizing the reliance on global variables can lead to more maintainable, reusable, and testable code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly