Python Lesson 10: Functions
A function is a reusable block of code that does one specific job. Define it once, call it anywhere. Functions are the building blocks of every program.
Defining and Calling a Function
# Define the function with def
def greet():
print("Hello! Welcome to Python!")
print("Learning to code is awesome!")
# Call it by name
greet() # runs the code inside
greet() # can call it many times!
Functions with Parameters
def greet_person(name):
print(f"Hello, {name}! Nice to meet you!")
greet_person("Alice") # Hello, Alice!
greet_person("Bob") # Hello, Bob!
def add(a, b):
print(f"{a} + {b} = {a + b}")
add(5, 3) # 5 + 3 = 8
add(10, 20) # 10 + 20 = 30
return — Get Values Back
def add(a, b):
return a + b # sends the result back to the caller
result = add(5, 3)
print(result) # 8
print(add(10, 20) * 2) # 60
def get_greeting(name):
return f"Hello, {name}!"
message = get_greeting("Alice")
print(message) # Hello, Alice!
Default Parameters
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob", "Good morning") # Good morning, Bob!
Variable Scope
x = 10 # global variable
def my_function():
y = 20 # local variable (only inside function)
print(x) # can read global
print(y) # can read local
my_function()
# print(y) ERROR! y does not exist outside function
🏋️ Practice Task
Create a function calculate_bmi(weight_kg, height_m) that returns BMI (weight / height squared). Ask user for weight and height. Print BMI and whether they are: underweight (<18.5), normal (18.5-25), or overweight (>25).
💡 Hint: bmi = weight / (height ** 2). Use round(bmi, 1) to round. Use if/elif/else to print the category.