🗂️ Lesson 7: Lists & Dictionaries
⏱️ Estimated time: 35 minutes | Difficulty: Intermediate
Organizing Data
Lists and Dictionaries are the most common ways to store collections of data in Python. One is an ordered list, the other is a set of key-value pairs.
What is a Function?
A function is a reusable block of code. Instead of writing the same code over and over, you create it once and use it many times!
Real-World Analogy:
🎂 Imagine a cookie recipe:
Without functions: You write down the entire recipe every time you want cookies
With functions: You write the recipe once, then just say "Make cookies!" whenever you want them
Creating a Function
def greet():
print("Hello!")
print("Welcome!")
Using a Function
def greet():
print("Hello!")
print("Welcome!")
# Call the function 3 times
greet()
greet()
greet()
Output:
Hello!
Welcome!
Hello!
Welcome!
Hello!
Welcome!
Functions with Parameters
Parameters are values you pass to a function:
def greet(name):
print("Hello,", name)
print("Nice to meet you!")
greet("Alice")
greet("Bob")
Output:
Hello, Alice
Nice to meet you!
Hello, Bob
Nice to meet you!
Functions with Return Values
Use return to send a value back from a function:
def add(a, b):
result = a + b
return result
answer = add(5, 3)
print(answer)
print(add(10, 20))
Output:
8
30
Multiple Parameters
def calculate_price(quantity, price_per_item):
total = quantity * price_per_item
return total
cost = calculate_price(5, 10)
print("Total cost:", cost)
Output:
Total cost: 50