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!
Questo esercizio fa parte del corso
Introduction to Functions in Python
Istruzioni dell'esercizio
- Modify the function header such that the function name is now
shout_all, and it accepts two parameters,word1andword2, in that order. - Concatenate the string
'!!!'to each ofword1andword2and assign toshout1andshout2, respectively. - Construct a tuple
shout_words, composed ofshout1andshout2. - Call
shout_all()with the strings'congratulations'and'you'and assign the result toyell1andyell2(remember,shout_all()returns 2 variables!).
Esercizio pratico interattivo
Prova a risolvere questo esercizio completando il codice di esempio.
# 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)