Functions Basics
Learn to create reusable code blocks with functions
What You'll Learn
- What functions are
- Creating functions
- Using parameters
- Returning values
What is a Function?
A function is a reusable block of code. Write it once, use it many times!
Like a recipe:
- Give it a name
- List the steps
- Use it whenever needed
Creating a Simple Function
def greet():
print("Hello!")
# Use the function
greet()
# Shows: Hello!Format:
def function_name():
# code hereFunctions with Parameters
Give the function information:
def greet(name):
print(f"Hello {name}!")
greet("John")
# Shows: Hello John!
greet("Sarah")
# Shows: Hello Sarah!Multiple Parameters
def introduce(name, age):
print(f"My name is {name}")
print(f"I am {age} years old")
introduce("John", 25)Output:
My name is John
I am 25 years old
Returning Values
Send back a result:
def add(a, b):
result = a + b
return result
total = add(5, 3)
print(total)
# Shows: 8Shorter way:
def add(a, b):
return a + bPractice Examples
Example 1: Calculate area
def calculate_area(length, width):
area = length * width
return area
room_area = calculate_area(10, 12)
print(f"Room area: {room_area}")
# Shows: Room area: 120Example 2: Check even/odd
def is_even(number):
if number % 2 == 0:
return True
else:
return False
print(is_even(4)) # True
print(is_even(7)) # FalseExample 3: Greet with time
def greet_time(name, time):
if time < 12:
print(f"Good morning, {name}!")
elif time < 18:
print(f"Good afternoon, {name}!")
else:
print(f"Good evening, {name}!")
greet_time("John", 9) # Good morning, John!
greet_time("Sarah", 15) # Good afternoon, Sarah!Default Parameters
Set default values:
def greet(name="Guest"):
print(f"Hello {name}!")
greet("John") # Hello John!
greet() # Hello Guest!def calculate_price(price, tax=0.08):
total = price + (price * tax)
return total
# With tax
print(calculate_price(100)) # 108.0
# Custom tax
print(calculate_price(100, 0.10)) # 110.0Multiple Return Values
Return more than one thing:
def get_stats(numbers):
total = sum(numbers)
count = len(numbers)
average = total / count
return total, average
my_total, my_avg = get_stats([10, 20, 30])
print(f"Total: {my_total}")
print(f"Average: {my_avg}")Real-World Examples
Example 1: Temperature converter
def celsius_to_fahrenheit(celsius):
fahrenheit = (celsius * 9/5) + 32
return fahrenheit
temp_f = celsius_to_fahrenheit(25)
print(f"25°C = {temp_f}°F")
# Shows: 25°C = 77.0°FExample 2: Calculate discount
def apply_discount(price, discount_percent):
discount = price * (discount_percent / 100)
final_price = price - discount
return final_price
original = 100
sale_price = apply_discount(100, 20)
print("Original: $" + str(original))
print("Sale: $" + str(sale_price))Example 3: Validate email
def is_valid_email(email):
if "@" in email and "." in email:
return True
else:
return False
print(is_valid_email("john@gmail.com")) # True
print(is_valid_email("invalid")) # FalseFunctions Calling Functions
def add(a, b):
return a + b
def multiply(a, b):
return a * b
def calculate(x, y):
sum_result = add(x, y)
product = multiply(x, y)
return sum_result, product
s, p = calculate(5, 3)
print(f"Sum: {s}, Product: {p}")
# Shows: Sum: 8, Product: 15Common Mistakes
Mistake 1: Forgetting parentheses
# Wrong
def greet:
print("Hello")
# Correct
def greet():
print("Hello")Mistake 2: Forgetting to call function
def greet():
print("Hello")
# This doesn't run the function
greet
# This runs it
greet()Mistake 3: Using return value without return
# Wrong - no return
def add(a, b):
result = a + b
total = add(5, 3)
print(total) # None
# Correct
def add(a, b):
return a + bMistake 4: Code after return
def greet():
return "Hello"
print("Hi") # Never runs!Quick Reference
Basic function:
def function_name():
# codeWith parameters:
def function_name(param1, param2):
# codeReturn value:
def function_name():
return valueDefault parameters:
def function_name(param="default"):
# codeWhy Use Functions?
1. Reusability: Write once, use many times
2. Organization: Break big problems into small pieces
3. Easier to fix: Fix in one place
4. Easier to read: Names explain what code does
Summary
- Functions are reusable code blocks
- Use
defto create functions - Parameters give input to functions
returnsends back output- Default parameters are optional
- Functions make code cleaner and reusable
What's Next?
Now let's learn advanced function concepts!