关键字 global
继续巩固您对作用域的掌握。本练习中,您将会在函数内使用关键字 global,去修改一个在全局作用域中定义的变量的值。
本练习是课程的一部分
Python 函数入门
练习说明
- 使用关键字
global来修改全局作用域中的对象team。 - 将全局作用域中的
team的值改为字符串"justice league",并把结果赋给team。 - 点击 "Submit" 按钮,看看执行您新定义的函数
change_team()后,名称team的值是如何变化的!
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create a string: team
team = "teen titans"
# Define change_team()
def change_team():
"""Change the value of the global variable team."""
# Use team in global scope
# Change the value of team in global: team
# Print team
print(team)
# Call change_team()
change_team()
# Print team
print(team)