开始使用免费开始使用

返回多个值的函数

在上一个练习中,您已经构造了元组、将元组赋值给变量,并完成了解包。现在,您将使用元组从函数中返回多个值。我们来更新 shout() 函数,使其返回多个值。不再只返回一个字符串,而是返回两个在末尾都连接了字符串 !!! 的字符串。

请注意,return x, yreturn (x, y) 的结果相同:前者在底层其实是把 xy 打包成了一个元组!

本练习是课程的一部分

Python 函数入门

查看课程

练习说明

  • 修改函数头,使函数名变为 shout_all,并按顺序接收两个参数 word1word2
  • 将字符串 '!!!' 分别连接到 word1word2 的末尾,并分别赋给 shout1shout2
  • 构造一个由 shout1shout2 组成的元组 shout_words
  • 调用 shout_all(),传入字符串 'congratulations''you',并将结果解包赋值给 yell1yell2(请记住,shout_all() 会返回 2 个变量!)。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# 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)
编辑并运行代码