Functions

Named, reusable blocks of code — write the logic once, run it as many times as you need.

Basics

A function is a named block of code that does one job, which you can call from anywhere in your program instead of rewriting the same logic repeatedly. Define one with def, a name, and parentheses (even if there's nothing inside them).

def greet(name):
    """Greets a person by name."""
    print("Hello,", name)

greet("ByteWise")
Hello, ByteWise

The text in triple quotes right under the def line is called a docstring — a short note for other programmers (or future you) explaining what the function does.

Return

return sends a value back to wherever the function was called, and immediately ends the function — any code written after it in that call won't run.

def add(x, y):
    return x + y

result = add(4, 5)
print(result)
print(add(2, 3) + 10)
9 15

A function with no return statement still "returns" something — it just gives back None by default. These are sometimes called void functions.

def shout(msg):
    print(msg.upper())

output = shout("hi")
print(output)
HI None

Arguments

Positional arguments are matched to parameters by order — the first value goes to the first parameter, and so on.

def describe(name, age):
    print(name, "is", age, "years old")

describe("ByteWise", 5)
ByteWise is 5 years old

Default arguments give a parameter a fallback value, used only when the caller doesn't provide one. Defaults always have to come last in the function definition.

def greet(name, greeting="Hello"):
    print(greeting, name)

greet("ByteWise")
greet("ByteWise", "Hey")
Hello ByteWise Hey ByteWise

Keyword arguments are passed by naming the parameter directly, so order stops mattering. If you mix the two, positional arguments have to come before keyword ones.

def describe(name, age):
    print(name, "is", age, "years old")

describe(age=5, name="ByteWise")
ByteWise is 5 years old

Scope

Scope determines where a variable name is visible. A global variable, declared outside any function, can be read from anywhere — including inside functions.

x = 10

def show():
    print(x)

show()
10

A local variable, declared inside a function, only exists while that function is running — it disappears once the function finishes, and can't be reached from outside it.

def set_value():
    y = 5
    print(y)

set_value()
print(y)
5 NameError: name 'y' is not defined

To actually create or modify a global variable from inside a function, use the global keyword.

def update():
    global count
    count = 1

update()
print(count)
1