Menu
Courses / python basic / Functions & Scope

Functions & Scope

07 / 10 Part of python basic




 

    ⚡ Topic 06 · Reusability
 

 


    Functions & Scope
 


 


    Write reusable, composable functions with parameters, return values, default arguments, and lambda expressions.
 


 

    ⏱ ~45 min
    🟡 Intermediate
    🏗️ Essential
 


 
 

   

     
     

Defining & Calling Functions


   

   

Use the def keyword. Functions run only when called, and can return values with return.


   

     

        functions.py
     

     
def greet(name):
    """Return a personalised greeting."""  # docstring
    return f"Hello, {name}!"

message = greet("Alice")
print(message)  # Hello, Alice!

   

 


 
 

   

     
     

Default & Keyword Arguments


   

   

Parameters can have default values, and callers can pass arguments by name for clarity.


   

     

        defaults.py
     

     
def power(base, exponent=2):
    return base ** exponent

print(power(3))                       # 9
print(power(2, 10))                   # 1024
print(power(exponent=3, base=4))     # 64

   

 


 
 

   

     
     

*args and **kwargs


   

   

Accept a variable number of positional (*args) or keyword (**kwargs) arguments.


   

     

        args_kwargs.py
     

     
def total(*numbers):
    return sum(numbers)

print(total(1, 2, 3, 4))  # 10

def profile(**info):
    for key, val in info.items():
        print(f"{key}: {val}")

profile(name="Alice", age=30)

   

 


 
 

   

     
     

Lambda Functions


   

   

Lambda creates small, anonymous one-expression functions — great for use as arguments to sorted(), map(), and filter().


   

     

        lambda.py
     

     
square = lambda x: x ** 2
print(square(5))  # 25

nums = [3, 1, 4, 1, 5]
sorted(nums, key=lambda x: -x)  # descending

   

 


 
 

   

     
     

Scope — the LEGB Rule


   

   

Python resolves variable names in this order: Local → Enclosing → Global → Built-in.


   

     

        scope.py
     

     
x = "global"

def outer():
    x = "enclosing"
    def inner():
        x = "local"
        print(x)  # local
    inner()
    print(x)      # enclosing

outer()
print(x)          # global

   

   

      💡 global & nonlocal keywords
     

Use global x inside a function to modify a global variable. Use nonlocal x to modify a variable in the enclosing (non-global) scope.