DEV Community

Cover image for Functions
Emilio Ochieng
Emilio Ochieng

Posted on

Functions

Defining and calling functions

A function is a self-contained, reusable block of code designed to perform one specific task. Instead of repeating the same instructions throughout a program, you package them once, give them a name, and call that name whenever the task needs doing.

def greet():
    print("Hello there!")

greet()   # calling the function
Enter fullscreen mode Exit fullscreen mode

def declares the function, followed by its name and parentheses. The indented lines beneath it are the function's body - the code that actually runs when the function is called.

Parameters and arguments

A function can accept input through parameters - placeholders defined in the function's signature - which get filled in with actual arguments when the function is called:

def greet(name):          # 'name' is the parameter
    print("Hello, " + name)

greet("Emilio")            # "Emilio" is the argument
Enter fullscreen mode Exit fullscreen mode

Functions can take multiple parameters, and can give them default values so an argument becomes optional:

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

greet("Emilio")                 # uses the default: "Hello, Emilio"
greet("Emilio", "Welcome back") # overrides it: "Welcome back, Emilio"
Enter fullscreen mode Exit fullscreen mode

Return values

A function can send a result back to whatever called it, using return. This is different from print(), which only displays something - return actually hands the value back so it can be stored, passed along, or used in further calculations.

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

total = add(100, 200)   # total now holds 300
print(total)
Enter fullscreen mode Exit fullscreen mode

Once a return statement runs, the function stops immediately - any code after it in the function body never executes.

Scope

Scope determines where a variable can be seen and used. A variable created inside a function (a local variable) only exists within that function — it disappears once the function finishes running, and code outside the function can't access it. A variable created outside any function (a global variable) can be read from anywhere, including inside functions.

message = "I'm global"

def show_message():
    local_note = "I'm local"
    print(message)      # works fine - global variables are visible inside functions
    print(local_note)

show_message()
print(local_note)       # this line would raise a NameError - local_note doesn't exist out here
Enter fullscreen mode Exit fullscreen mode

Practical examples

A function that takes a list of prices and returns the total - reusable anywhere a total needs calculating, instead of rewriting the summing logic each time:

def calculate_total(prices):
    total = 0
    for price in prices:
        total += price
    return total

cart = [180, 320, 85]
print(calculate_total(cart))   # 585
Enter fullscreen mode Exit fullscreen mode

What I understood from this

The distinction between print() and return was the one that mattered most in practice. Early on I'd write a function that "worked" because it printed the right answer to the screen - but then couldn't figure out why using that function's result in another calculation gave an error. print() only shows a value; it doesn't hand it back to the program. return is what actually makes a function's output usable elsewhere - total = add(100, 200) only works because add returns a value for total to catch. Scope followed a similar lesson: a variable defined inside a function is genuinely gone once that function ends, which is exactly why return exists - it's the sanctioned way to get a value out of that otherwise-sealed local scope.

Top comments (0)