何时使用GLOBAL变量?

问题描述 投票:4回答:1

我试图在一个函数中返回一个变量,该函数分配给接受用户输入的另一个变量。例如(间距已关闭,但这仅是因为我没有尝试修复它):

def learn_languageinfo_choice():
    try:
        global num
        num = int(input("Please enter the key corresponding to the language you would like to learn about: "))
        print("You chose " + most_used_languages[num] + ".")
        global choice
        choice = most_used_languages[num]
        return choice
    except:
        print("You must enter a corresponding key... ")
        learn_languageinfo_choice()

def user_choice(choice):
    if num == 1:
      .....

我之前将most_used_languages预定义为字典(不包括在内)该程序可以按预期完成,但我觉得以后可能会感到困惑如果我将选择变量设置为全局变量,是否有理由将其返回?我可能只是对返回的作用感到困惑,甚至无法返回函数中定义的变量。]​​>

我试图在一个函数中返回一个变量,该函数分配给接受用户输入的另一个变量。例如(间距是关闭的,但这仅是因为我没有尝试修复它):def ...

python return global
1个回答
-2
投票

下面是使用全局变量的方式,

© www.soinside.com 2019 - 2024. All rights reserved.