Python Anonymous Functions :

Scope of Variables :

All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python :

  • Global variables
  • Local variables

Global vs. Local variables :

Variables that are defined inside a function body have a local scope, and those defined outside have a global scope. This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope. Following is a simple example :

Example :

  1. result = 0; #This is global variable.
  2. def sum(num1,num2) :
  3. result = num1 + num2;
  4. print("Inside/Local variable: result - ",result);
  5. sum(10, 20);
  6. print("Outside/Global variable: result - ",result);
  7. input()

Output :

python Global vs. Local variables

The Anonymous (Lambda) Functions :

Lambda functions are called anonymous because Lambda are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions. A lambda function can take any number of arguments, but can only have one expression.

Syntax :

lambda arguments : expression

Example :

  1. sum = lambda num1, num2: num1 + num2;
  2. # Now you can call sum as a function
  3. print ("Value of total : ", sum( 10, 20 ))
  4. print ("Value of total : ", sum( 20, 20 ))
  5. input()

Output :

python anonymous function example

Note :

  • Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
  • An anonymous function cannot be a direct call to print because lambda requires an expression.
  • Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.

Next Update


We have a YouTube channel for live game streaming purposes, the channel name is "NightHawk". You can visit our gaming channel and support us, Thank you