← Back to list

Lambda Functions, Variable Scope, global Keyword & Types of Python Errors

A lambda function is an anonymous function — a function without a name, written in a single line.

Anuj Chhetri · 2026-04-01 14:00 · 1 claps · 3.8 min read
#python #data-science #lambda #python-error #variablescope
Open on Medium ↗
Wiki topics: ML · Machine Learning ☁️ · DevOps & Cloud 🔬 · Science · General

Lambda Functions, Variable Scope, global Keyword & Types of Python Errors

A lambda function is an anonymous function — a function without a name, written in a single line.

Normal function:  def fun(a, b, c...): statement1; statement2; return
Lambda function:  function_name = lambda arguments: expression

The key rules:

Can take any number of arguments

Can only have one expression (one line)

Automatically returns the result of that expression

Example 1 — Basic Lambda (one argument)

my_function = lambda a: a + 10

my_function(5)    # 15

Equivalent def version:

def my_function(a):
    return a + 10

Same result — lambda is just shorter.

Example 2 — Lambda with Two Arguments

my_function = lambda a, b: a + b

my_function(5, 4)    # 9

Example 3 — Lambda Inside a def (Function Factory)

This is powerful — a function that returns a lambda:

def myfun(n):
    return lambda a: a * n    # returns a new function

z = myfun(2)    # z is now: lambda a: a * 2
y = myfun(3)    # y is now: lambda a: a * 3

print(z(5))     # 10   (5 * 2)
print(y(7))     # 21   (7 * 3)

Example 4 — Lambda with Conditional (if/else)

even_odd = lambda a: "Even" if a % 2 == 0 else "Odd"

x = even_odd(5)
print(x)    # Odd

Example 5 — Find Greatest of Two Numbers

greatest = lambda a, b: a if a > b else b

x = greatest(10, 5)
print(x)    # 10

lambda vs def — When to Use Which?

 lambda                                    def 
One line only                         Multiple lines
Anonymous                             Has a name
Simple, short, inline                 Complex, reusable
Return Automatic                      Explicit `return`
Good for simple tasks                 Better for complex logic

Variable Scope

Local variable -> exists only inside a function -> cannot use it outside Global variable -> defined at top-level, not inside any function

Local Variable — Stays Inside the Function

def sqrtt(x):
    y = x ** 2      # y is LOCAL — born here, dies here
    return y

z = sqrtt(10)
# print(z)   <- this works fine

print(y)    # NameError: name 'y' is not defined

y lives only inside sqrtt(). Once the function ends, y is gone. Trying to access it outside causes a NameError.

When a Function Has Its Own Local Variable

x = 3 * 2     # global x = 6
y = 1         # global y = 1

def sub(z):
    y = 10            # LOCAL y — different from global y = 1
    return y - z

print(sub(x))     # 10 - 6 = 4

The y = 10 inside sub() is a completely separate variable from the global y = 1. They share the name but live in different scopes.

UnboundLocalError — The Dangerous Mistake

x = 9

def adding():
    x += 1       # tries to modify x — but Python treats x as local!
    print(x)

adding()
# UnboundLocalError: local variable 'x' referenced before assignment

Why? The moment Python sees x += 1 inside a function, it decides x is local. But local x was never assigned — so it can't be read either. Crash.

The global Keyword — Modify a Global Variable

x = 10    # global variable

def change_value():
    x = 5                           # creates a LOCAL x — doesn't touch global
    print(f"Inside function, x = {x}")

change_value()
print(f"outside function, x = {x}")

# Inside function, x = 5
# outside function, x = 10    <- global unchanged!

To actually modify the global variable, use global:

x=10            # global variable
def change_global_value():
    global x        # tells Python: use the GLOBAL x
    x = 20

change_global_value()
print(f"After modifying --> outside function, x = {x}")

# After modifying --> outside function, x = 20   <- global changed!

Types of Python Errors

Every Python error tells you exactly what went wrong — if you know how to read them. Today I studied all 7 major error types.

Error Type 1 — SyntaxError

Happens before the program even runs. Python can’t parse your code.

x = 10
if x == 10        # <- missing colon!
    print("x is 10")

# SyntaxError: expected ':'

Fix: Always end if, for, while, def lines with :

Error Type 2 — NameError (Runtime Error)

Happens while the program runs. You’re using a name Python doesn’t know.

def sumation(x, y):    # notice: 'sumation' not 'summation'
    return x + y

a = 5
b = 10
x = summation(a, b)    # <- calling wrong name
print(x)

# NameError: name 'summation' is not defined

Fix: Check spelling. Python is case-sensitive — Summationsummation.

Error Type 3 — TypeError

Wrong type used in an operation.

x = "10"     # string
y = 5        # integer
z = x + y   # <- can't add str and int

# TypeError: can only concatenate str (not "int") to str

Fix: Convert types first — int(x) + y or x + str(y).

Error Type 4 — IndexError

Accessing an index that doesn’t exist.

x = "Hello"    # indices: 0,1,2,3,4
x[5]           # index 5 doesn't exist!

# IndexError: string index out of range

Fix: Use len(x) - 1 as the maximum valid index.

Error Type 5 — AttributeError

Calling a method that doesn’t exist on that object.

my_string = "Hello World!"
my_string.uper()    # typo: should be .upper()

# AttributeError: 'str' object has no attribute 'uper'

Error Type 6 — ZeroDivisionError

Dividing by zero — mathematically undefined.

10 / 0

# ZeroDivisionError: division by zero

Fix: Add a check before dividing — if b != 0: result = a / b.

Error Type 7 — Logical Error

The most dangerous error — Python does not tell you. The code runs fine but gives the wrong answer.

def calculate_factorial(n):
    result = 1
    for i in range(1, n):         # BUG: should be range(1, n+1)
        result = result * i
    return result

calculate_factorial(5)    # returns 24 <- WRONG! should be 120

Why wrong? range(1, 5) gives 1, 2, 3, 4 — misses the 5. The correct loop is range(1, n+1).

Logical errors need careful testing — Python can’t detect them for you.


메타데이터
post_id
18bdd1dbbc72
slug
lambda-functions-variable-scope-global-keyword-types-of-python-errors-18bdd1dbbc72
url
https://medium.com/@dotsyko/lambda-functions-variable-scope-global-keyword-types-of-python-errors-18bdd1dbbc72
canonical_url
https://medium.com/@dotsyko/lambda-functions-variable-scope-global-keyword-types-of-python-errors-18bdd1dbbc72
author_url
https://medium.com/@dotsyko
status
ok
fetched_at
2026-06-09 15:37:30