關鍵字 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)