Why Functions Transform Code
Functions let you write once, use anywhere. They make code
readable, reusable, and maintainable - the hallmarks of professional software.
| Problem |
Function Solution |
| 100 lines of repeated code |
1 function call |
| Hard to debug mess |
Isolated testable units |
| Changing 1 thing = 50 changes |
Change function once |
| Beginner spaghetti code |
Professional modular structure |
Basic Functions
Function Definition
def function_name(parameters):
"""Docstring"""
# Code block
return result
Hello World Function
def greet(name):
"""Greet someone by name"""
message = f"Hello, {name}!"
return message
# Usage
print(greet("Alice")) # Hello, Alice!
print(greet("Bob")) # Hello, Bob!
No Parameters
def get_pi():
return 3.14159
print(get_pi()) # 3.14159
Parameters Mastery
Positional Arguments
def add(a, b):
return a + b
result = add(5, 3) # 8
Keyword Arguments
def calculate_area(length, width):
return length * width
area = calculate_area(width=10, length=5) # 50
Default Parameters
def greet(name="World"):
return f"Hello, {name}!"
print(greet()) # Hello, World!
print(greet("Alice")) # Hello, Alice!
*args & **kwargs (Advanced)
def sum_all(*numbers):
return sum(numbers)
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print(sum_all(1, 2, 3, 4, 5)) # 15
print_info(name="Alice", age=25, city="NYC")
return vs print
# โ BAD - Only prints
def bad_add(a, b):
print(a + b)
result = bad_add(5, 3) # Prints 8
print(result) # None!
# โ
GOOD - Returns value
def good_add(a, b):
return a + b
result = good_add(5, 3) # Returns 8
print(result * 2) # 16 โ
Multiple Return Values
def divide_and_remainder(a, b):
quotient = a // b
remainder = a % b
return quotient, remainder
q, r = divide_and_remainder(10, 3)
print(f"10 รท 3 = {q} remainder {r}") # 3 remainder 1
Variable Scope
x = 10 # Global scope
def my_function():
x = 20 # Local scope (doesn't affect global)
print(f"Inside: {x}") # 20
my_function()
print(f"Outside: {x}") # 10
# To modify global (rarely needed)
def change_global():
global x
x = 30
Function Parameters = Local Copies
def increment(n):
n += 1
return n
age = 25
new_age = increment(age)
print(age) # 25 (unchanged)
print(new_age) # 26
Production Functions
Math Utility Library
def circle_area(radius):
return 3.14159 * radius ** 2
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def format_currency(amount):
return f"${amount:,.2f}"
# Usage
print(circle_area(5)) # 78.54
print(is_prime(17)) # True
print(format_currency(1234.5)) # $1,234.50
Text Processing
def clean_text(text):
return text.strip().lower().replace(" ", " ")
def word_count(text):
words = clean_text(text).split()
return len(words)
message = " Hello World "
print(word_count(message)) # 2
Function Challenges
1. Calculator Functions
Create add(), subtract(), multiply(), divide() functions with error handling
2. Password Validator
Write validate_password() checking length, uppercase, numbers, special chars
3. BMI Calculator
calculate_bmi(weight, height) โ weight category + health advice
4. Text Analyzer
analyze_text(text) โ word count, char count, avg word length, most common letter
Professional Function Patterns
1. Single Responsibility
# โ
GOOD - One job per function
def calculate_total(items):
return sum(items)
def apply_tax(total, rate=0.08):
return total * (1 + rate)
def format_receipt(total):
return f"Total: ${total:.2f}"
2. Docstrings & Type Hints
def calculate_tip(bill: float, percentage: float = 0.15) -> float:
"""
Calculate restaurant tip amount.
Args:
bill: Pre-tax bill amount
percentage: Tip percentage (default 15%)
Returns:
Tip amount in dollars
"""
return bill * (percentage / 100)
Function Superpowers Unlocked!
โก Professional Applications:
Calculator App
Modular math functions
Text Processor
Clean, reusable utilities
Form Validator
Input sanitization library
Unit Converter
Multiple conversion functions
Math Toolkit
Geometry, statistics, finance
Next: Lists & Dictionaries โ File I/O โ Full Applications