🐍 Python Tutorial: Functions & Scope

Functions help you organize code into reusable blocks. They allow you to group related code, avoid repetition, and create modular programs. Understanding scope ensures variables behave the way you expect inside and outside functions.


1. Defining Functions

Define a function using the def keyword, followed by a name and parentheses:

def greet():
    print("Hello, world!")

greet()

The function greet() can be called multiple times without rewriting its code.


2. Parameters and Arguments

You can pass values to functions through parameters:

def greet(name):
    print(f"Hello, {name}!")

greet("Alice")

3. Return Values

Use the return statement to send data back from a function:

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

result = add(3, 5)
print(result)

4. Variable Scope

Variables created inside a function are local and can’t be accessed outside. Variables outside are global:

x = 10  # global

def modify():
    x = 5  # local to function
    print("Inside:", x)

modify()
print("Outside:", x)

Use global x inside a function if you really need to modify a global variable (not recommended unless necessary).


Additional Resources & References


← Back : Control FlowNext: Data Structures β†’