To start this guide, download this zip file.
Practice with Tuples
These problems will help you practice with tuples.
Registering participants
First, let’s write a simple program to register participants for an event. We want to collect the first name, last name, and age for each participant. The program should then print out the list of participants. Here is a simple diagram showing how this should work:
We can translate this drawing into code by writing a simple main()
function:
def main():
participants = register_participants()
print_participants(participants)
if __name__ == '__main__':
main()
Notice how the list of participants returned by register_participants()
is
stored in a variable and then that variable is given to print_participants()
to print them out.
A list of tuples
We are going to keep track of each participant’s info as a tuple of
(first, last, age)
. Then we are going to put those tuples in a list. So if we
register three people, the list stored in the participants
variable will have
something like this:
[('Emma', 'Walker', 24), ('Jorge', 'Rodriguez', 23), ('Min', 'Young', 24)]
Registering participants
Next, here is a diagram of how to register participants:
-
We start with an empty list.
-
We get a participant. This function returns either a tuple with participant info or None.
-
If the participant is None, break and return the list.
-
Otherwise, append the tuple to a list of participants and get another one.
We can translate this into code in the register_participants()
function:
def register_participants() -> list[tuple[str, str, int]]:
people = []
while True:
participant = get_participant()
if participant is None:
break
people.append(participant)
return people
- Start an empty list.
- Use a
while True
loop to keep getting participants untilget_participant()
returnsNone
. - If the return value is ever
None
, we break out of the loop at that point. - Otherwise we append the tuple for a participant to a list of people who are registered.
- When the loop finishes, return the list.
Notice how this code doesn’t care if get_participant()
returns a string or a
tuple. We will have it return a tuple, like ('Emma', 'Walker', 24)
, but we can
write our code the same either way.
Getting a participant
Here is a diagram of how to get a participant:
We can translate that into code in the get_participant()
function:
def get_participant() -> tuple[str, str, int] | None:
print('Register a participant (or enter no first name to stop)')
first = input('First name: ')
if first == '':
return None
last = input('Last name: ')
age = int(input('Age: '))
return (first, last, age)
- Get the first name.
- If that is empty, then return
None
- Otherwise get the rest of the info and return a tuple with all of the info.
This is how to return a tuple from a function:
return (first, last, age)
Printing participants
Finally, we can write a function to print the participants:
def print_participants(participants: list[tuple[str, str, int]]):
for first, last, age in participants:
print(f'{last}, {first} ({age})')
We loop through the tuples and unpack them using for ... in
. Then we can
print each part of the tuple using a formatted string.
Running the program
You can run this program using registration.py
in the zip file linked above.
When you run it, you should see somehting like this:
Register a participant (or enter no first name to stop)
First name: Emma
Last name: Walker
Age: 24
Register a participant (or enter no first name to stop)
First name: Jorge
Last name: Rodriguez
Age: 23
Register a participant (or enter no first name to stop)
First name: Min
Last name: Young
Age: 24
Register a participant (or enter no first name to stop)
First name:
Walker, Emma (24)
Rodriguez, Jorge (23)
Young, Min (24)
Meal Planning
Write a program that creates a meal plan for several days. Get a list of meals and print them out. Each individual meal needs a grain, vegetable, and fruit.
For example:
Plan a meal
Grain: rice
Vegetable: broccoli
Fruit: strawberry
Plan a meal
Grain: pasta
Vegetable: peas
Fruit: cranberry
Plan a meal
Grain: bread
Vegetable: carrots
Fruit: apples
Plan a meal
Grain:
You planned 3 meals:
Grain: rice, Vegetable: broccoli, Fruit: strawberry
Grain: pasta, Vegetable: peas, Fruit: cranberry
Grain: bread, Vegetable: carrots, Fruit: apples
Planning
See if you can write this program with a friend. You have starter code in the
zip file above, in the file called meal_planner.py
:
def main():
# Write code here
pass
if __name__ == '__main__':
main()
Start by decomposing the problem into functions! What are the functions you
would use in main()
?
Maybe you recognized that this problem is quite similar to the registration program above. You can use two functions in main:
def main():
meals = get_meals()
print_meals(meals)
get_meals()
should return a list of tuples, with each one storing (grain, vegetable, fruit)print_meals()
should use the list of tuples to print out the meal information.
Getting the meals
To get the meals, we can follow the same steps as we did when gretting the participants, above:
def get_meals() -> list[tuple[str, str, str]]:
meals = []
while True:
meal = get_meal()
if meal is None:
break
meals.append(meal)
return meals
- Start with an empty list.
- Loop forever
- Get a meal.
- If the meal is None, break
- Otherwise append the meal to the list
- Return the meals
Getting one meal
To get one meal, we can do the same as when getting one participant:
def get_meal() -> tuple[str, str, str] | None:
print('Plan a meal')
grain = input('Grain: ')
if grain == '':
return None
vegetable = input('Vegetable: ')
fruit = input('Fruit: ')
return grain, vegetable, fruit
- Print the instructions.
- Get the grain.
- If the grain is an empty string, return
None
. - Otherwise get the rest of the meal info (vegetable, fruit) and return a tuple of (grain, vegetable, fruit)
Notice that in this case, we left off the parentheses when returning the tuple:
return grain, vegetable, fruit
This is OK! Python still understands that we are returning a tuple.
Printing the meals
To print the meals, we can loop through them and use unpacking:
def print_meals(meals: list[tuple[str, str, str]]):
print()
print(f'You planned {len(meals)} meals:')
for grain, vegetable, fruit in meals:
print(f'Grain: {grain}, Vegetable: {vegetable}, Fruit: {fruit}')