Introduction:
In Python, understanding how variables are stored and used in functions is important. This page introduces key concepts that help us organise and use data effectively in functions. We’ll look at:
- Local vs Global Variables: Differentiating between variables defined inside a function (local) and those defined outside (global).
- Passing Multiple Parameters: How to pass multiple values into a function, including positional and keyword arguments.
- Returning Multiple Values: How to return more than one value from a function, using tuples.
Let’s explore each concept with clear explanations and examples.
Local vs Global Variables
What is a Local Variable?
A local variable is defined inside a function and can only be accessed within that function. It is created when the function is called and is destroyed when the function finishes.
What is a Global Variable?
A global variable is defined outside of all functions and can be accessed by any function in the program. Global variables exist throughout the program's runtime.
Example:
# Global variable x = 10 def example_function(): # Local variable y = 5 print("Inside the function, y =", y) print("Inside the function, x =", x) example_function() print("Outside the function, x =", x)
In this example, x
is a global variable and can be accessed both inside and outside the function. y
is a local variable and can only be accessed inside example_function()
.
Let’s see this in action:
Predict:
Look at the following code. What do you think will happen when it’s run? Will z
be printed both inside and outside the function?
def test_scope(): z = 7 print("Inside function, z =", z) test_scope() print("Outside function, z =", z)
Hint: Since z
is a local variable inside the function, it won’t exist outside of the function. What do you think will happen when Python tries to print z
outside the function?
Run:
Let’s run the following code and see what happens when we try to print the local variable z
both inside and outside the function.
Outcome Explained:
- The function is called first and so the function will print the value of
z
inside the function (z = 7
). - When we try to then print
z
outside the function, Python will raise a NameError becausez
only exists within the function (local scope).
Passing Multiple Parameters
Functions can accept multiple parameters, allowing them to work with more than one piece of data. We can pass these arguments either positionally (by their order) or using keyword arguments.
Example: Positional Parameters
In this function, we pass two parameters and the order matters.
def greet(first_name, last_name): print(f"Hello, {first_name} {last_name}!") greet("John", "Doe")
Example: Keyword Arguments
We can also pass parameters by explicitly naming them, so the order doesn’t matter.
def greet(first_name, last_name): print(f"Hello, {first_name} {last_name}!") greet(last_name="Doe", first_name="John")
Let’s see these examples in action:
Investigate:
Try changing the order of the arguments in the following code. What happens if we switch the positions of a
and b
?
Returning Multiple Values from Functions
In Python, a function can return multiple values at once. These values are returned as a tuple, which can be unpacked into multiple variables.
Example:
def calculate(a, b): sum_result = a + b product_result = a * b return sum_result, product_result # Unpacking the returned tuple into two variables sum_val, product_val = calculate(4, 5) print(f"Sum: {sum_val}, Product: {product_val}")
In this example, the function calculate()
returns two values: the sum and the product of a
and b
. We then unpack these values into two separate variables.
Let’s see this in action:
Modify:
Below is a function that calculates the difference and the division of two numbers. However, it’s missing the return statement. Can you add the return statement so that the function returns both values?