Functions that return multiple values
In the previous exercise, you constructed tuples, assigned tuples to variables, and unpacked tuples. Here you will return multiple values from a function using tuples. Let's now update our shout()
function to return multiple values. Instead of returning just one string, we will return two strings with the string !!!
concatenated to each.
Note that the return statement return x, y
has the same result as return (x, y)
: the former actually packs x
and y
into a tuple under the hood!
This exercise is part of the course
Introduction to Functions in Python
Exercise instructions
- Modify the function header such that the function name is now
shout_all
, and it accepts two parameters,word1
andword2
, in that order. - Concatenate the string
'!!!'
to each ofword1
andword2
and assign toshout1
andshout2
, respectively. - Construct a tuple
shout_words
, composed ofshout1
andshout2
. - Call
shout_all()
with the strings'congratulations'
and'you'
and assign the result toyell1
andyell2
(remember,shout_all()
returns 2 variables!).
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Define shout_all with parameters word1 and word2
def shout_all(____, ____):
"""Return a tuple of strings"""
# Concatenate word1 with '!!!': shout1
# Concatenate word2 with '!!!': shout2
# Construct a tuple with shout1 and shout2: shout_words
# Return shout_words
return shout_words
# Pass 'congratulations' and 'you' to shout_all(): yell1, yell2
# Print yell1 and yell2
print(yell1)
print(yell2)