開始使用免費開始

關鍵字 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)
編輯並執行程式碼