Understanding Global and Local Variables, Lambda Functions, and Recursive Functions in Python

name1 = 'dfg'

return
def ChangeGlobalVari2():
    name1 = 'dfg'
    return
print(name1)

When executing ChangeGlobalVari1(), the output will be dfg.

When executing ChangeGlobalVari2(), the output will be ddd.

If a global variable is of mutable type like a list or dictionary, there's no need to declare it as global.

li = [66]  # Mutable type; no need for global declaration

print(li)
print(id(li))

def changeList(l):
    l.append(23)
    print(id(l))
    return

changeList(li)
print(li)

Output:

[66]
id value
id value
[66, 23]

Anonymous Funcsions Using Lambda

Features

  • Defined using the lambda keyword.
  • No function name reqiured.
  • Expression after colon must be a single expression, not a statement.
  • Implicitly returns the result of the expression.

Syntax

variable = lambda param1, param2, ...: expression

The variable holds the result of the expression.

Usage

def sum(a, b):
    return a + b

SUM = lambda a, b: a + b

print(sum(23, 4))
print(SUM(4, 5))

Output:

27
9

Conditoinal Logic with Lambda

MaxNum = lambda a, b: a if a > b else b
print(MaxNum(3, 5))

Output:

5

Recursive Functions

  • A function that calls itself within its definition.
  • Must have a base case to prevent infinite recursion.

Example: Factorial Calculation

def func1(n):
    if n == 1:
        return 1
    else:
        return n * func1(n - 1)

print(func1(4))

Output:

24

Listing All Files in a Directory Using Recursion

import os

def findFile(filePath):
    fileList = os.listdir(filePath)
    for item in fileList:
        print(item)

Tags: python functions Global Variables local variables lambda

Posted on Sun, 02 Aug 2026 16:22:51 +0000 by bb_xpress