Functions

2 min read

Write Once, Use Anywhere – The Power of Functions

As your programs get larger, repeating code becomes messy. That’s where functions come in.

Functions help you:

  • Reuse code easily
  • Break big problems into smaller pieces
  • Write cleaner, maintainable programs

1. πŸ§ͺ Defining and Calling Functions #

A function is defined using the def keyword.

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

Calling the function:

greet()

πŸ’‘ Why use functions?
Imagine needing to greet users in 10 places β€” just call greet() instead of copy-pasting the print line.


2. 🎁 Parameters, Arguments, and Default Values #

🧾 Parameters #

These are placeholders in the function definition.

πŸ“¨ Arguments #

These are actual values you pass when calling the function.

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

greet("Hannan")  # Output: Hello, Hannan

βš™οΈ Default Parameters #

Provide a default value that gets used if no argument is passed.

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

greet()            # Output: Hello, Guest
greet("Hannan")    # Output: Hello, Hannan

3. 🧾 Return Statements #

Functions can return values instead of just printing them.

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

result = add(5, 3)
print("Sum:", result)  # Output: Sum: 8

Without return, functions just perform an action β€” but with return, they give back results you can use later.


4. πŸ“¦ Variable Scope: Local vs. Global #

Understanding where your variables “live” is key to writing bug-free code.

πŸ”’ Local Scope #

Variables declared inside functions.

def test():
    x = 10  # local variable
    print(x)

test()
# print(x)  # ❌ Error: x is not defined outside

🌐 Global Scope #

Variables declared outside functions are available globally.

x = 5

def show():
    print(x)  # accessing global variable

show()  # Output: 5

✏️ Modifying Global Variables #

You must use global keyword to change a global variable inside a function.

x = 10

def modify():
    global x
    x = 20

modify()
print(x)  # Output: 20

πŸ’Ό Real-World Use Case: Bill Calculator Using Functions #

Let’s create a Bill Calculator for a store or restaurant using functions.

πŸ”§ Features: #

  • Accepts multiple items with price and quantity
  • Calculates total
  • Adds tax
  • Prints final amount

πŸ’» Full Code: #

# Function to calculate total bill for an item
def calculate_item_total(price, quantity):
    return price * quantity

# Function to apply tax
def apply_tax(total, tax_rate=0.10):  # 10% tax by default
    return total + (total * tax_rate)

# Main function to run the bill calculator
def bill_calculator():
    total = 0
    print("🧾 Welcome to Hannan's Store")
    
    while True:
        item = input("Enter item name (or type 'done' to finish): ")
        if item.lower() == 'done':
            break
        try:
            price = float(input("Enter price of the item: "))
            quantity = int(input("Enter quantity: "))
            item_total = calculate_item_total(price, quantity)
            total += item_total
            print(f"{item.title()} total: Rs.{item_total:.2f}\n")
        except ValueError:
            print("❌ Invalid input. Please enter numbers only.\n")

    total_with_tax = apply_tax(total)
    print(f"\nπŸ’° Final Total (with tax): Rs.{total_with_tax:.2f}")

# Run the calculator
bill_calculator()

πŸ§ͺ Output Sample: #

🧾 Welcome to Hannan's Store
Enter item name (or type 'done' to finish): Apple
Enter price of the item: 50
Enter quantity: 3
Apple total: Rs.150.00

Enter item name (or type 'done' to finish): done

πŸ’° Final Total (with tax): Rs.165.00

🧠 What You Learned: #

ConceptUsage in Code
Function definitiondef calculate_item_total(...)
Arguments & Default valuesapply_tax(total, tax_rate=0.10)
Return valuesReturning total and tax
Local/Global variablestotal as local, inputs as params
ReusabilityOne function, used many times

πŸ’‘ Bonus Tips: #

  • Use functions for:
    • Validations
    • Clean UI formatting
    • Repeated calculations
  • Group related functions in modules
  • Use *args and **kwargs for more dynamic functions (coming in advanced topics!)

πŸš€ What’s Next? #

Coming up next:

πŸ”„ Lists & Collection Handling
Learn how to use Python’s most powerful built-in collections β€” with a real-world use case like Student Marks Manager

Want me to continue with that now? Or package this chapter for sharing or training material? Just say the word!

Updated on June 9, 2025