Cyber Services / All lessons / Python Programming / Functions and Scope

Functions and Scope

Module 11 of 31 · 3 min read · Free to read

MODULES ↓ Command blocks have a COPY button
Reusable Code and Variable Visibility

What Are Functions?

A function is a named block of reusable code that performs a specific task. Functions help you avoid repetition, improve readability, and make programs modular and testable.

  • Defined once, called many times
  • Can accept inputs (parameters) and return outputs
  • Encapsulate logic—hide complexity behind a simple interface
  • Enable code reuse across projects

Basic Function Syntax

def function_name(parameter1, parameter2):
    # body of the function
    return result  # optional

Core Concepts with Examples

1. Simple Function (No Parameters)
def greet():
    print("Hello, welcome to Python!")

greet()  # Output: Hello, welcome to Python!
2. Function with Parameters
def say_hello(name):
    print(f"Hello, {name}!")

say_hello("Ali")  # Hello, Ali!
3. Function with Return Value
def square(x):
    return x * x

result = square(5)
print(result)  # 25
4. Multiple Parameters
def add(a, b):
    return a + b

total = add(10, 20)
print(total)  # 30
5. Default Parameter Values
def greet(name="Guest"):
    print(f"Hello, {name}!")

greet()           # Hello, Guest!
greet("Sara")     # Hello, Sara!
6. Keyword Arguments
def describe_pet(animal, name):
    print(f"I have a {animal} named {name}.")

# Order doesn't matter with keywords
describe_pet(name="Whiskers", animal="cat")
7. Returning Multiple Values
def min_max(numbers):
    return min(numbers), max(numbers)

nums = [3, 1, 4, 1, 5]
low, high = min_max(nums)
print(f"Min: {low}, Max: {high}")  # Min: 1, Max: 5
8. Function That Returns Nothing (None)
def log_message(msg):
    print(f"[LOG] {msg}")

result = log_message("System started")
print(result)  # None

Understanding Scope

Scope defines where a variable can be accessed in your code. Python uses LEGB rule:

  • Local: Inside the current function
  • Enclosing: In a nested function’s outer function
  • Global: At the top level of the module
  • Built-in: Predefined names like len, print
9. Local vs Global Variables
name = "Global Ali"  # global variable

def my_function():
    name = "Local Ali"  # local variable
    print(name)  # Local Ali

my_function()
print(name)  # Global Ali
10. Modifying Global Variable (Use global)
counter = 0

def increment():
    global counter
    counter += 1

increment()
print(counter)  # 1
11. Enclosing Scope (Nested Functions)
def outer():
    x = "outer"
    def inner():
        print(x)  # accesses 'x' from outer scope
    inner()

outer()  # Output: outer
12. Modifying Enclosing Variable (nonlocal)
def outer():
    x = "original"
    def inner():
        nonlocal x
        x = "modified"
    inner()
    print(x)  # modified

outer()

Practical & Real-World Examples

13. Input Validation Function
def get_positive_number():
    while True:
        try:
            num = int(input("Enter a positive number: "))
            if num > 0:
                return num
            else:
                print("Number must be positive!")
        except ValueError:
            print("Invalid input! Enter a number.")

# Usage
value = get_positive_number()
print(f"You entered: {value}")
14. Calculate Average of List
def average(numbers):
    if not numbers:
        return 0
    return sum(numbers) / len(numbers)

grades = [85, 90, 78, 92]
print(f"Average grade: {average(grades):.2f}")  # 86.25
15. Check if Number is Prime
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

print(is_prime(17))  # True
print(is_prime(18))  # False
16. Reusable Menu Function
def show_menu(options):
    print("\nPlease choose an option:")
    for i, opt in enumerate(options, 1):
        print(f"{i}. {opt}")
    return len(options)

choices = ["View Balance", "Deposit", "Withdraw", "Exit"]
total = show_menu(choices)
print(f"Total options: {total}")
17. Function as Argument (Higher-Order)
def apply_operation(numbers, func):
    return [func(x) for x in numbers]

data = [1, 2, 3, 4]
squared = apply_operation(data, lambda x: x**2)
print(squared)  # [1, 4, 9, 16]
18. Docstrings for Documentation
def calculate_area(length, width):
    """
    Calculate the area of a rectangle.
    
    Args:
        length (float): The length of the rectangle.
        width (float): The width of the rectangle.
    
    Returns:
        float: The area (length × width).
    """
    return length * width

# Access docstring
print(calculate_area.__doc__)

Best Practices

  • Give functions clear, descriptive names (e.g., calculate_tax, not calc).
  • Keep functions short and focused—one task per function.
  • Use default parameters to make functions flexible.
  • Avoid modifying global variables—prefer return values.
  • Write docstrings for every non-trivial function.
  • Test functions with edge cases (empty input, zero, negatives).

Key Takeaways

  • Functions = reusability + modularity.
  • Parameters pass data in; return sends data out.
  • Variables have scope: local, enclosing, global, built-in.
  • Use global and nonlocal sparingly—they can make code harder to debug.
  • Well-designed functions are the building blocks of clean, maintainable programs.
Modules (31) ← Python Programming