13.4 Tuples as Return Values
From Foundations of Python ProgrammingGNU FDL 1.3Original pagePython1 class period2 exercises2 graded tests
13.4 Tuples as Return Values
Functions can return tuples as return values. This is very useful --- we often want to know some batsman's highest and lowest score, or we want to find the mean and the standard deviation, or we want to know the year, the month, and the day, or if we're doing some ecological modeling we may want to know the number of rabbits and the number of wolves on an island at a given time. In each case, a function (which can only return a single value), can create a single tuple holding multiple elements.
For example, we could write a function that returns both the area and the circumference of a circle of radius r.
def circleInfo(r):
""" Return (circumference, area) of a circle of radius r """
c = 2 * 3.14159 * r
a = 3.14159 * r * r
return (c, a)
print(circleInfo(10))
Again, we can take advantage of packing to make the code look a little more readable on line 4
def circleInfo(r):
""" Return (circumference, area) of a circle of radius r """
c = 2 * 3.14159 * r
a = 3.14159 * r * r
return c, a
print(circleInfo(10))
It's common to unpack the returned values into multiple variables.
def circleInfo(r):
""" Return (circumference, area) of a circle of radius r """
c = 2 * 3.14159 * r
a = 3.14159 * r * r
return c, a
print(circleInfo(10))
circumference, area = circleInfo(10)
print(circumference)
print(area)
circumference_two, area_two = circleInfo(45)
print(circumference_two)
print(area_two)
Check your Understanding
Check your understanding: a multiple-choice question in the book.
Exercise 1
Define a function called information that takes as input, the variables name, birth_year, fav_color, and hometown. It should return a tuple of these variables in this order.
Open the
01folder and editmain.py. Run Tests checks it.
Exercise 2
Define a function called info with the following required parameters: name, age, birth_year, year_in_college, and hometown. The function should return a tuple that contains all the inputted information.
Open the
02folder and editmain.py. Run Tests checks it.
For teachers
13.4 Tuples as Return Values
Students read Foundations of Python Programming's “Tuples as Return Values” in CS Room and work through its 2 Python coding exercises (2 graded).
- Time: 1 class period
- Tests: 2 in 2 graded exercises, set up for you when you import the lesson
Exercises
| Folder | Grading | Tests |
|---|---|---|
01 | Autograded | 1 |
02 | Autograded | 1 |