Understanding Functions, Variable Scopes, and Lambda Functions in Python
In this chapter, we’ll go through functions, one of the core building blocks in Python. Functions allow you to organize code, reuse logic, and make your programs cleaner and more efficient. In this chapter, we’ll explore how to define functions with and without return statements, understand the differences between local and global variables, and how Python handles variable scopes. We’ll also go over more advanced topics like default arguments, keyword arguments, and passing a variable number of arguments. To wrap things up, we’ll take a look at lambda functions, which are anonymous functions that can be used in situations where you need simple one-liner functions. By the end of this chapter, you’ll have a solid grasp of how to use functions effectively in Python.
Functions in Python
Example 1: Defining a Function Without a Return Statement:
def table(a):
b = 1
while b <= 5:
print("%d * %d = %d" % (a, b, b * a))
b += 1
table(5)
Output:
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
Explanation:
This function, table(a)
, takes a single parameter “a
” and prints the multiplication table for “a"
from 1 to 5. It does not return any value because it directly prints the result inside the loop. The loop runs as long as “b"
is less than or equal to 5, and on each iteration, it prints the result of a * b
.
Example 2: Defining a Function with a Return Statement:
def average(a, b, c):
d = (a + b + c) / 3
return d
result = average(10, 20, 30)
print(result)
#Output : 20.0
Explanation:
Here, the function average(a, b, c)
calculates the average of three numbers. It returns the result, which is captured in the variable result
. The function uses the return
statement to pass back the value of “d"
, making it available outside the function. The key difference from the previous example is that this function returns a value rather than just printing the result.
Variable Scope in Python: Local and Global Variables
Local Variables : Variables declared inside a function are local variables, which means they only exist within the function and cannot be accessed outside it.
def average(a, b, c):
d = (a + b + c) / 3
return d
result = average(10, 20, 30)
print(d) # This will cause an error
#Output : NameError: name 'd' is not defined
In this code, “d"
is a local variable inside the average()
function. Trying to print “d"
outside the function causes a NameError
because the variable “d"
does not exist outside the scope of the function. This illustrates the concept of local variables being confined to the function where they are defined.
Global Variables : Global variables are defined outside any function and can be accessed within functions unless explicitly overridden.
a = 10
def average(b, c):
print("a is", a)
d = (a + b + c) / 3
return d
print(average(20, 30))
#Output :
a is 10
20.0
Explanation:
Here, the variable “a"
is declared globally. When the function average()
is called, it can access the global variable “a"
without needing to pass it as an argument. The global variable “a"
is used within the function, and no local variable “a"
is created.
Local Variable with Same Name as Global :
a = 10
def average(b, c):
a = 40
d = (a + b + c) / 3
print("local variable 'a' is", a)
average(20, 30)
print("global variable 'a' is still", a)
#Output:
local variable 'a' is 40
global variable 'a' is still 10
Explanation:
In this example, even though there is a global variable “a"
, the function average()
declares a new local variable “a"
with the value 40. This local variable is used inside the function, and the global “a"
remains unchanged. Python prioritizes local variables over global ones within a function when the names are the same.
Using “global"
to Modify Global Variables :
a = 10
def average(b, c):
global a
print("variable 'a' inside function is", a)
d = (a + b + c) / 3
a = 40 # This modifies the global variable 'a'
print("average is", d)
average(20, 30)
print("global variable 'a' is now", a)
#Output :
variable 'a' inside function is 10
average is 20.0
global variable 'a' is now 40
Explanation:
Using the “global"
keyword, the function average()
can modify the global variable “a"
. Without “global"
, the assignment a = 40
would create a local variable “a"
, but here it modifies the global “a"
directly. This is useful when you need to change the value of a global variable within a function.
Call by Object Reference
When passing a mutable object like a list to a function, changes made to the object inside the function are reflected outside the function as well.
def add_to_list(x, y):
x.append(y)
a = []
add_to_list(a, 10)
add_to_list(a, 20)
add_to_list(a, 30)
print(a)
#Output:
[10, 20, 30]
Explanation:
In this example, the function add_to_list(x, y)
modifies the list x
by appending the value y
. Since lists are mutable, the changes made to x
inside the function affect the list a
outside the function. This behavior is known as call by object reference in Python.
Default Argument Values
def average(a, b, c=30):
print((a + b + c) / 3)
average(10, 20)
average(10, 20, 60)
#Output :
20.0
30.0
Explanation:
In this function, the third parameter “c"
has a default value of 30. When the function is called with only two arguments (10
and 20
), it uses the default value of “c"
as 30. However, when the function is called with three arguments (10, 20, 60
), it overrides the default value with 60.
Keyword Arguments
def repeat(string, count):
a = 1
while a < count:
print(string)
a += 1
repeat(count=3, string="python")
#Output :
python
python
python
Explanation:
Python allows you to pass arguments by specifying the parameter name. This flexibility is called keyword arguments, allowing you to pass values in any order by specifying the parameter name. In this example, the repeat()
function is called using count=3
and string="python"
.
Variable Number of Arguments
def sum(a, b, *c):
result = a + b
for tmp in c:
result += tmp
print(result)
sum(10, 20)
sum(10, 20, 30)
sum(10, 20, 30, 40)
#Output:
30
60
100
Explanation:
In Python, the *c
in the function definition allows the function to accept an arbitrary number of additional arguments. These extra arguments are collected into a tuple and can be accessed inside the function. In this example, the sum()
function sums all the arguments passed to it, regardless of how many there are.
Lambda Functions in Python
Lambda functions are anonymous functions that can take any number of arguments but have only one expression. They are commonly used for short, simple functions.
cube = lambda x: x ** 3
print(cube(5)) # 125
even = lambda x: True if x % 2 == 0 else False
print(even(10)) # True
sum = lambda x, y: x + y
print(sum(10, 5)) # 15
Explanation:
Lambda functions are useful for writing small, one-liner functions. In the examples above, cube
calculates the cube of a number, even
checks if a number is even, and sum
adds two numbers. Lambda functions don’t require the use of the def
keyword and are often used when a function object is needed temporarily.
Using Lambda Functions with filter()
, map()
, and reduce()
a = [1, 2, 3, 4, 5]
# Using map with lambda
cube = lambda x: x ** 3
print(list(map(cube, a))) # [1, 8, 27, 64, 125]
# Using filter with lambda
even = lambda x: x % 2 == 0
print(list(filter(even, a))) # [2, 4]
# Using reduce with lambda
from functools import reduce
sum = lambda x, y: x + y
print(reduce(sum, a)) # 15
Explanation:
map()
applies the lambda function to each element of the lista
.filter()
returns only the elements of the lista
that satisfy the condition in the lambda function.reduce()
reduces the lista
by applying the lambda function cumulatively, in this case, summing all the elements.
Programming Exercises :
- Create a function to check whether a given number is prime. Use this function with a list of numbers to print only the prime numbers from that list.
- Write a Python program to find the factorial of a number using a recursive function.
-
- Create a function to find and return the smallest element from a given list.
- Create another function to return the position of a given element in a list.
- Create a function to delete the element at a given position in the list.
- Using the above three functions, repeatedly find, print, and remove the smallest number from the input list. Continue this process until the input list is empty, and this will effectively sort the numbers in ascending order.
- Create a function to check if a given year is a leap year or not. Use this function to print only the leap years from a list of years.
- Write a Python program that defines a function to calculate the sum of squares of numbers in a list. Use this function to return the sum of squares for any given list of numbers.
- Create a function that takes a list of numbers and returns the average of the numbers in the list.
- Write a Python program to define a function that counts the number of vowels in a given string. Use this function to count and print the vowels from a list of strings.
- Create a function that accepts two lists and returns a new list containing only the elements that are common between the two lists.
- Write a Python program that defines a function to reverse a given string. Use this function to reverse a list of strings and print the result.
- Create a function that takes a list of numbers and returns the maximum and minimum numbers in the list.
- Write a Python program that defines a function to calculate the greatest common divisor (GCD) of two numbers using recursion.
We’d love to hear your feedback and suggestions about this article. Feel free to reach out to us using the WhatsApp number below.
About The Author:
Sajith Achipra has been a trainer and testing consultant at Zframez Technologies since 2009. With 15+ years of experience, he specializes in networking, Python, development, and testing. He conducts online courses to help students and professionals enhance their skills. You can reach him on WhatsApp at +91 8884 884 844 for your training and testing requirements.