New Batch Starts on 16th Oct.
Module: Network Fundamentals (L2 L3 Protocol Testing)
Timing: 07:00 AM to 08:00 AM IST (Weekdays)
Sign Up Now !

Chapter 10: Python Functions, Variable Scopes, and Lambda Expressions

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:

Output:

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:

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.

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.

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 :

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 :

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.

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

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

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

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.

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()

Explanation:

  • map() applies the lambda function to each element of the list a.
  • filter() returns only the elements of the list a that satisfy the condition in the lambda function.
  • reduce() reduces the list a by applying the lambda function cumulatively, in this case, summing all the elements.


We’d love to hear your feedback and suggestions about this article. Feel free to reach out to us using the WhatsApp number below.

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.