DEV Community

Cover image for Python Functions
Alex Murithi
Alex Murithi

Posted on

Python Functions

Python Functions: Defining, Parameters, Return Values, and Scope

Functions are reusable blocks of code that perform a specific task. They help organize programs, reduce repetition, and make code easier to maintain.

1. Defining and Calling Functions

A function is defined using the def keyword, followed by its name and parentheses. Inside the function, you write the code that should run when the function is called.

def greet():
    print("Hello, welcome to Python!")

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

Output

Hello, welcome to Python!
Enter fullscreen mode Exit fullscreen mode

Why This Matters
Instead of writing the same greeting multiple times, you define it once and call it whenever needed. This makes your code shorter and easier to maintain.

2. Parameters and Arguments

Parameters are variables defined inside the function parentheses. Arguments are the actual values you pass when calling the function.

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

greet_user("Alice")
greet_user("Brian")
Enter fullscreen mode Exit fullscreen mode

Output

Hello, Alice!
Hello, Brian!
Enter fullscreen mode Exit fullscreen mode

Default parameters can also be used to provide fallback values:

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

greet_user()
greet_user("Cynthia")
Enter fullscreen mode Exit fullscreen mode

Output

Hello, Guest!
Hello, Cynthia!
Enter fullscreen mode Exit fullscreen mode

3. Return Values

Functions can return results using the return keyword. This allows you to store or reuse the output.

def calculate_discount(price, rate=0.10):
    discount = price * rate
    return price - discount

final_price = calculate_discount(2000)
print(f"Final Price: Ksh {final_price}")
Enter fullscreen mode Exit fullscreen mode

Output

Final Price: Ksh 1800.0
Enter fullscreen mode Exit fullscreen mode

Why Return Values Matter
Returning values makes functions flexible. Instead of just printing results, you can use them in further calculations or store them in variables.

3. Scope - Local vs Global Variables

Scope determines where a variable can be accessed.

Local variables exist only inside a function.

Global variables exist outside and can be accessed anywhere.

message = "Global message"

def show_message():
    message = "Local message"
    print(message)

show_message()
print(message)
Enter fullscreen mode Exit fullscreen mode

Output

Local message
Global message
Enter fullscreen mode Exit fullscreen mode

Why Scope Matters
Understanding scope prevents bugs. For example, if you accidentally overwrite a global variable inside a function, it can affect the rest of your program.

Practical Examples
1. VAT Calculator
Instead of repeating VAT calculations for every item, define a function:

def add_vat(price, rate=0.14):
    vat = price * rate
    total = price + vat
    return total

print(f"Item 1: Ksh {add_vat(1000)}")
print(f"Item 2: Ksh {add_vat(800)}")
print(f"Item 3: Ksh {add_vat(600)}")
Enter fullscreen mode Exit fullscreen mode

Output

Item 1: Ksh 1140.0
Item 2: Ksh 912.0
Item 3: Ksh 684.0
Enter fullscreen mode Exit fullscreen mode

2. Student Report Formatter

def print_divider():
    print("=" * 40)

def student_info(name, score):
    print_divider()
    print(f"Student: {name}")
    print(f"Score: {score}")
    print_divider()

student_info("Amina", 87)
student_info("Brian", 98)
Enter fullscreen mode Exit fullscreen mode

Output

========================================
Student: Amina
Score: 87
========================================
========================================
Student: Brian
Score: 98
========================================
Enter fullscreen mode Exit fullscreen mode

3. Banking Example

def deposit(balance, amount):
    return balance + amount

def withdraw(balance, amount):
    if amount > balance:
        print("Insufficient funds")
        return balance
    return balance - amount

balance = 1000
balance = deposit(balance, 500)
balance = withdraw(balance, 300)
print(f"Final Balance: Ksh {balance}")
Enter fullscreen mode Exit fullscreen mode

Output

Final Balance: Ksh 1200
Enter fullscreen mode Exit fullscreen mode

Conclusion

Functions are used to organize and reuse code.

Pass parameters makes functions flexible.

Return values are used to capture results.

Understanding scope helps avoid variable conflicts.

Mastering functions makes Python programs cleaner, more modular, and easier to maintain.

Top comments (0)