Where a name can be used, how long it lives, and how code is shared between files are the remaining ideas needed to write well organised programs.

Scope and Lifetime of Variables

The scope of a variable is the part of the program in which it can be used. A variable created inside a function is local and exists only while the function runs, which is its lifetime. A variable created outside all functions is global and can be read anywhere. To change a global variable inside a function, the keyword global must be declared. Python looks for a name first in the local scope, then in any enclosing function, then in the global scope, and finally among the built-in names.

Definition: Scope. The region of a program in which a variable name is valid and can be used.

Lambda Functions

A lambda function is a small anonymous function written in one line as lambda arguments: expression. It returns the value of the expression. For example, square = lambda x: x * x. Lambda functions are mostly used as arguments to functions such as sorted(), map() and filter().

The assert Statement

The assert statement checks that a condition is True and raises an AssertionError if it is not. It is used to catch mistakes early, as in assert n > 0, "n must be positive".

Importing a User Defined Module

A module is a Python file containing functions and variables that other programs can use. If a file mymath.py defines a function cube(), another program can write import mymath and call mymath.cube(3), or write from mymath import cube and call cube(3). The module is found if it is in the same folder as the program. A name such as import mymath as mm gives it a shorter alias.

Table 2.4: Local and global variables

Feature Local Global
Created Inside a function Outside functions
Visible Only in the function Everywhere
Lifetime During the call Whole program
Change inside function Allowed Needs the global keyword

Example 2.4: Scope, lambda and assert

Problem: Show the scope of a variable, a lambda that squares a number, and sorting words by length with a lambda.

Solution:

  1. Create a global x and a local x inside a function and print both.
  2. Define square with lambda.
  3. Sort a list of words with key=lambda w: len(w).

Result: The local x does not change the global x, square(6) is 36, and the words are ordered from the shortest to the longest.

x = 10
def show():
    x = 99
    print("inside", x)
show()
print("outside", x)
square = lambda v: v * v
print(square(6))
words = ["banana", "fig", "apple", "kiwi"]
print(sorted(words, key=lambda w: len(w)))
n = 5
assert n > 0, "n must be positive"
print("assert passed")

Output

inside 99
outside 10
36
['fig', 'kiwi', 'apple', 'banana']
assert passed

Common mistakes

  • Assigning to a global name inside a function without the global keyword, which creates a new local variable.
  • Writing a lambda with several statements. It allows only one expression.
  • Giving a module the same name as a standard module, which causes the wrong one to be imported.

Key takeaways

  • Local variables live only during the function call.
  • global lets a function change a global variable.
  • lambda creates a small anonymous function.
  • assert raises AssertionError when a condition is False.

Practice questions

  1. Define the scope of a variable.
  2. Write a lambda that adds 10 to a number.
  3. How is a user defined module used in another program?

Answers to the practice questions

  1. The part of the program in which the variable can be used.
  2. lambda x: x + 10.
  3. By writing import module_name.

Sources

  • Official BCA syllabus Python Programming, course code 26BCA403SEC01, Unit II