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: #
Concept | Usage in Code |
---|---|
Function definition | def calculate_item_total(...) |
Arguments & Default values | apply_tax(total, tax_rate=0.10) |
Return values | Returning total and tax |
Local/Global variables | total as local, inputs as params |
Reusability | One 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!