Introduction
In Python, a function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
In this lab, you will learn the fundamentals of creating and using functions in Python. You will practice defining functions that accept arguments, using keyword arguments for clarity, returning values, understanding the difference between local and global variable scopes, and creating concise anonymous functions with lambda.
Function Arguments
In this step, you will learn how to define a function that accepts arguments. A function can take arguments, which are values you pass to the function when you call it.
Note: If you are not familiar with using WebIDE (VS Code like), please learn it first at this lab.
Let's create a function that takes a name argument and prints a personalized greeting.
First, open the file arguments.py from the file explorer on the left.
Next, copy and paste the following code into the arguments.py file. This code defines a function say_hello that takes one argument, name.
## Define a function that takes one argument
def say_hello(name):
print(f'Hello {name}')
## Call the function with a string argument
say_hello('Carlos')
say_hello('Wanda')
say_hello('Rose')
Now, let's run the script. Open a terminal in the WebIDE and execute the following command:
python3 arguments.py
You should see the function being called with different names, producing a unique greeting for each one.
Hello Carlos
Hello Wanda
Hello Rose
This demonstrates how arguments make functions flexible and reusable.
Keyword Arguments
In this step, you will learn how to use keyword arguments to improve code readability. When a function has multiple parameters, you can specify which argument corresponds to which parameter by using the parameter's name. This is called a keyword argument.
When you use positional arguments, the order in which you pass them matters. With keyword arguments, the order doesn't matter, which makes your code more explicit and easier to understand.
Open the file keywords.py from the file explorer. Copy and paste the following code into it.
## Function with multiple parameters
def say_hi(name, greeting):
print(f"{greeting} {name}")
## Positional arguments: order matters
print("Calling with positional arguments:")
say_hi('John', 'Hello')
## Keyword arguments: order doesn't matter, more readable
print("\nCalling with keyword arguments:")
say_hi(name='Anna', greeting='Hi')
Now, run the script from the terminal:
python3 keywords.py
You will see the output from both function calls. Notice how keyword arguments allow you to pass values in any order.
Calling with positional arguments:
Hello John
Calling with keyword arguments:
Hi Anna
Return Values
In this step, you will explore how to use the return statement to make a function produce an output. While print() displays a value to the console, return sends a value back from the function. This returned value can be stored in a variable or used in other expressions.
Let's create a function that takes two numbers, adds them, and returns the result.
Open the file returns.py and add the following code. The function sum_two_numbers calculates the sum and uses the return keyword to output the result.
## Function that returns a value using return statement
def sum_two_numbers(number_1, number_2):
return number_1 + number_2
## Call function and store the returned value
result = sum_two_numbers(7, 8)
print(result)
Execute the script in the terminal:
python3 returns.py
The output will be the value that the function returned, which was stored in the result variable and then printed.
15
Local and Global Scope
In this step, you will discover the difference between local and global variable scopes. A variable's scope determines where in your code it can be accessed.
- Global Scope: Variables defined outside of any function are in the global scope and can be accessed from anywhere in the code, including inside functions.
- Local Scope: Variables created inside a function are in that function's local scope. They only exist within that function and cannot be accessed from the outside.
Let's first see what happens when you try to access a local variable from the global scope. If you were to run the following code, it would raise a NameError because local_variable is not defined in the global scope.
## This code will cause an error
global_variable = 'I am available everywhere'
def some_function():
print(global_variable)
local_variable = "only available within this function"
print(local_variable)
## This will raise NameError because local_variable doesn't exist here
## print(local_variable)
The global Statement
If you need to modify a global variable from within a function, you must explicitly tell Python you are doing so with the global statement.
Open the file scope.py and add the following code. Here, the spam function uses the global keyword to modify the global variable eggs.
## Use 'global' keyword to modify global variable from inside function
def spam():
global eggs ## Declare that we're modifying the global variable
eggs = 'spam' ## This changes the global variable
eggs = 'global'
print(f"Before calling spam(), eggs is: {eggs}")
spam() ## Function modifies global variable
print(f"After calling spam(), eggs is: {eggs}")
Now, run the script:
python3 scope.py
Observe the output. The value of the global variable eggs is permanently changed by the function call.
Before calling spam(), eggs is: global
After calling spam(), eggs is: spam
Lambda Functions
In this step, you will learn to create anonymous, single-line functions using the lambda keyword. A lambda function can have any number of arguments but can only have one expression. They are useful for creating small, temporary functions without the overhead of a standard def function definition.
For example, a regular function to add two numbers:
## Regular function definition
def add(x, y):
return x + y
This is equivalent to the following lambda function:
## Lambda function: anonymous function defined in one line
add = lambda x, y: x + y
Lambdas can also work as lexical closures, meaning they can "remember" a value from the enclosing scope where they were created. Let's create a function that returns a lambda.
Open the file lambdas.py and add the following code. The make_adder function takes a number n and returns a new lambda function that adds n to any number x.
## Lambda closure: lambda function that captures a variable from the outer scope
def make_adder(n):
return lambda x: x + n ## Lambda captures 'n' from the outer function
## Create a function that adds 3
plus_3 = make_adder(3)
## Use the new function
result = plus_3(4) ## This will be 4 + 3
print(result)
Run the script from your terminal:
python3 lambdas.py
The output shows the result of calling the lambda function that was created and returned by make_adder.
7
You can create other adders as well, for example plus_5 = make_adder(5), which would create a function that adds 5 to its argument.
Summary
In this lab, you have explored the core concepts of functions in Python. You learned how to define functions and pass information to them using arguments. You practiced using both positional and keyword arguments to make your function calls clearer. You also learned how to make functions produce results with the return statement, how to manage variable accessibility with local and global scopes, and how to use the global keyword to modify variables outside a function. Finally, you were introduced to the power and conciseness of anonymous lambda functions for creating simple, single-line functions and closures.



