using tuples to return multiple values

    xiaoxiao2022-07-13  161

    # Define shout_all with parameters word1 and word2 def shout_all(word1, word2): # Concatenate word1 with '!!!': shout1 shout1 = word1 + '!!!' # Concatenate word2 with '!!!': shout2 shout2 = word2 + '!!!' # Construct a tuple with shout1 and shout2: shout_words shout_words = (shout1, shout2) # Return shout_words return shout_words # Pass 'congratulations' and 'you' to shout_all(): yell1, yell2 yell1, yell2 = shout_all('congratulations', 'you') # Print yell1 and yell2 print(yell1) print(yell2) # Define three_shouts def three_shouts(word1, word2, word3): """Returns a tuple of strings concatenated with '!!!'.""" # Define inner def inner(word): """Returns a string concatenated with '!!!'.""" return word + '!!!' # Return a tuple of strings return (inner(word1), inner(word2), inner(word3)) # Call three_shouts() and print print(three_shouts('a', 'b', 'c')) # Define echo def echo(n): """Return the inner_echo function.""" # Define inner_echo def inner_echo(word1): """Concatenate n copies of word1.""" echo_word = word1 * n return echo_word # Return inner_echo return inner_echo # Call echo: twice twice = echo(2) # Call echo: thrice thrice = echo(3) # Call twice() and thrice() then print print(twice('hello'), thrice('hello')) # Define echo_shout() def echo_shout(word): """Change the value of a nonlocal variable""" # Concatenate word with itself: echo_word echo_word = word * 2 # Print echo_word print(echo_word) # Define inner function shout() def shout(): """Alter a variable in the enclosing scope""" # Use echo_word in nonlocal scope nonlocal echo_word # Change echo_word to echo_word concatenated with '!!!' echo_word += '!!!' # Call function shout() shout() # Print echo_word print(echo_word) # Call function echo_shout() with argument 'hello' echo_shout('hello')
    最新回复(0)