INSTACK 360

Functions: Definition & Return Values

Stop writing spaghetti code. Learn how to encapsulate logic into reusable Functions to make your code modular and clean.

Intermediate 5 min read

Why Functions?

As your programs grow, writing the same block of code over and over becomes a nightmare. Functions allow you to write a block of code once, give it a name, and reuse it anywhere. This keeps your codebase DRY (Don't Repeat Yourself).

Defining a Function

Use the def keyword to create a function. You can design it to accept input data (Parameters).

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

# Calling the function
greet_user("Alice")

Returning Data

A function that just prints something is okay, but usually, we want our functions to process data and hand the result back to us. We do this using the return keyword. Once a function hits a return statement, it immediately exits.

def calculate_discount(price, discount_percent):
    discount_amount = price * (discount_percent / 100)
    final_price = price - discount_amount
    return final_price

# The function hands back the math result, which we store in a variable
checkout_total = calculate_discount(100, 20)