4 Functions Explained
Key Concepts
Functions in Python are reusable blocks of code that perform specific tasks. They help in organizing code, making it more modular and easier to maintain. The key concepts include:
- Defining Functions
- Function Parameters and Arguments
- Return Values
- Scope and Lifetime of Variables
1. Defining Functions
A function in Python is defined using the def
keyword, followed by the function name and parentheses. The code block within every function is indented.
Example:
def greet(): print("Hello, World!")
To call the function, use the function name followed by parentheses:
greet()
2. Function Parameters and Arguments
Parameters are variables listed inside the parentheses in the function definition. Arguments are the values passed to the function when it is called.
Example:
def greet(name): print(f"Hello, {name}!") greet("Alice")
In this example, name
is a parameter, and "Alice" is an argument.
3. Return Values
Functions can return values using the return
statement. This allows the function to send data back to the caller.
Example:
def add(a, b): return a + b result = add(3, 5) print(result)
Here, the function add
returns the sum of its parameters, which is then printed.
4. Scope and Lifetime of Variables
The scope of a variable determines where in the code the variable is accessible. Variables defined inside a function are local to that function and cannot be accessed outside of it.
Example:
def example_function(): local_var = 10 print(local_var) example_function() # print(local_var) # This will cause an error
In this example, local_var
is a local variable and cannot be accessed outside the function.
Putting It All Together
By understanding these key concepts, you can create and use functions effectively in Python. Functions help in organizing code, making it more modular and easier to maintain.
Example:
def calculate_area(radius): pi = 3.14159 return pi * radius ** 2 def display_area(area): print(f"The area is: {area}") radius = 5 area = calculate_area(radius) display_area(area)
In this example, the calculate_area
function computes the area of a circle, and the display_area
function prints the result.