Instructions on Tuples for Bundling Related Data in a Specific Format:
- Consider latitude and longitude coordinates that specify a point on the surface of the Earth. This is a pair of numbers that we want to be able to bundle together to represent a location; tuples are ideal for this. For example, if we store latitude as the first element in the tuple, and longitude as the second, Ithaca, NY, USA is approximately located at:
1Ithaca_NY = (42.439723, -76.496595)Questions:
In our position tuple above, latitude appears first and longitude is second. On what continent would you land if you misinterpreted the tuple and switched the order of the two elements? (Hint: Find a web site that lets you enter coordinates to find a position on the earth.)
- South America
- Africa
- Antarctica
- Asia
- Australia
- Europe
-
Imagine weβre storing dates as tuples of three integers that encode (YEAR, MONTH, DAY), where MONTH runs from 1 through 12 to indicate the months January through December, and DAY runs from 1 through however many days are in that MONTH. If you were presented with the Python statement date = (2019, 4, 7), how would you extract the day?
-
date[0:2]
-
date[3]
-
date[2]
Instructions on Tuples for Retruning Multiple Values from a Function:
- One common situation where tuples are used to bundle related data in a specific order occurs when we want to return multiple values from a function.
- The below code block represents an example with the function sum_and_difference(x, y), which returns both the sum and the difference of two inputs x and y.
1def sum_and_difference(x,y):
2 return x+y, x-y- Because the object that is returned by the function is a tuple, any variable that is assigned to the result of that function call is also a tuple.
Unpack the Tuple
- We can either assign that result to a single variable (of type tuple), or we can unpack the values in the tuple directly into multiple variables.
- For example, we could either write result = sum_and_difference(10, 2) (in which case the sum would be the first element of the result tuple, and the difference the second), or we can write xysum, xydiff = sum_and_difference(10, 2).
Questions:
-
What is returned by the statement sum_and_difference(10, 20)?
-
30 and -10
-
30 and 10
-
(30, -10)
-
(30) + (-10)
-
Given the function definition for sum_and_difference, which of the following would be valid Python statements? (Check all that apply.)
-
result = sum_and_difference(10,20)
-
a, b = sum_and_difference(10,20)
-
x, y, z = sum_and_difference(10,20)
In the statement a, b = sum_and_difference(10, 20), what is the value of b?
- (30, -10)
- 30
- -10
- 20