Welcome to Module 4! Up until now, if you wanted to perform a specific task (like calculating a tax or greeting a user) three different times in your program, you had to copy and paste that code three times.
In programming, we have a rule called DRY: Don’t Repeat Yourself. To follow this rule, we use Functions.
1. What is a Function?
A function is a named block of code that performs a specific task. You “define” it once, and then you can “call” it (use it) whenever you need it.
Think of it like a recipe in a cookbook. The recipe is the definition, and actually cooking the meal is the call.
The Code:
Python
# 1. Defining the function
def say_hello():
print("Hello there!")
print("Welcome to Module 4.")
# 2. Calling the function
say_hello()
say_hello()
2. Parameters: Giving Data to Functions
Functions become much more powerful when you give them information to work with. These pieces of information are called Parameters.
The Code:
Python
def greet_person(name):
print("Hello, " + name + "!")
greet_person("Alice")
greet_person("Bob")
In this example, name is the parameter. “Alice” and “Bob” are the data we send into that parameter.
3. The return Statement
Sometimes, you don’t want the function to just print something. You want it to do a calculation and give the answer back to you so you can use it later.
The Code:
Python
def add_numbers(a, b):
return a + b
# We save the 'returned' answer into a variable
total = add_numbers(10, 5)
print("The total is: " + str(total))
4. Local vs. Global Scope
A quick but important rule: variables created inside a function stay inside that function. This is called Local Scope.
Python
def my_function():
x = 10 # This x only exists inside here
print(x)
my_function()
# print(x) <-- This would cause an error!
🎓 Module 4 Final Project: “The Tip Calculator” 💰
Let’s build a tool that helps friends split a bill at a restaurant.
The Challenge:
- Create a function called
calculate_tip. - The function should take two parameters:
bill_amountandtip_percentage. - The function should return the total amount to pay (Bill + Tip).
- Ask the user for their bill and tip, call the function, and print the final result.
The Solution:
Try to structure the function before looking at the code.
Python
# 1. Define the function def calculate_tip(bill, tip_percent): tip_amount = bill * (tip_percent / 100) return bill + tip_amount
2. Get user input
user_bill = float(input(“How much was the bill? “)) user_tip = float(input(“What percentage tip (e.g. 15)? “))
3. Use the function
final_price = calculate_tip(user_bill, user_tip) print(“Your total bill with tip is: $” + str(final_price))
Next Up: In Module 5, we’ll learn how to handle large amounts of data using Lists and Dictionaries!
