如何避免声明全局变量?

时间:2018-01-07 21:19:20

标签: python global-variables

我是一个Python新手。我写了这段代码,但听说声明全局变量并不是一个好习惯。在这种情况下,编写此函数的正确方法是什么?

index = 0

def level_selection():
    global index
    level = raw_input("Choose the desired level of difficulty: easy, medium or hard")
    if level.lower() == "easy":
        return level1
    if level.lower() == "medium":
        return level2
    if level.lower() == "hard":
        return level3 
    else:
        print "Error"
        index += 1
        if index < 3:
            return level_selection()
        return

level1 = "You selected easy"
level2 = "You selected medium"
level3 = "You selected hard"

3 个答案:

答案 0 :(得分:0)

另外,如果你真的需要全局变量,那就是拥有一个包含你的索引的类成员变量。

class VARS(object):
    index = 0  
VARS.index += 1
print(VARS.index)
>1

答案 1 :(得分:0)

您在此程序中的目的是允许用户输入最多3个错误值。

您可以将index作为参数传递,该参数计算用户输入的错误,并通过递归调用函数来保留此值

使用该方法查看完全重写。

def level_selection(index):

    level1, level2, level3 = "level1", "level2","level3"

    level = input("Choose the desired level of difficulty: easy, medium or hard")
    if level.lower() == "easy":
        return level1
    if level.lower() == "medium":
        return level2
    if level.lower() == "hard":
        return level3 
    else:
        print("Error")
        index -= 1
        if index > 0:
            return level_selection(index)

    return

print(level_selection(3))

答案 2 :(得分:0)

如果您是python的新手,我强烈建议您使用python版本3 python逐行读取代码,这意味着在分配变量之前不能调用它。
全局变量可以在函数和类中访问,或者通过其他意义在变量内部继承函数和类,而不需要使用全局变量。
作为一个好习惯:

  • 如果您要使用 if语句
  • ,请始终尝试使用 else 语句
  • 将参数传递给函数,以获得更多动态程序,而不是使用静态内容。

所以在你的情况下,代码将是:

index = 0 #global scope

def level_selection(dx):
    my_local_index = dx #creating a new variale

    level1 = "You selected easy" #local variables
    level2 = "You selected medium" # not accessible outside of this scope
    level3 = "You selected hard" 

    level = raw_input("Choose the desired level of difficulty: easy, medium or hard")
    if level.lower() == "easy":
        return level1
    if level.lower() == "medium":
        return level2
    if level.lower() == "hard":
        return level3 
    else:
        print "Error"
        my_local_index += 1
        if my_local_index < 3:
            return level_selection(my_local_index)
        else:
            exit()

# calling the function and passing a argument to it
level_selection(index) 
相关问题