在python

时间:2016-03-28 21:49:33

标签: python python-3.x

我正在做一个学校项目,我需要一些帮助在功能之间进行通信。这是我到目前为止所得到的

def difficuilty():
level = 0
while level >=4 or level == 0:
    level = int(input("Please enter the difficulty (1/2/3)"))
    if level == 1:
        yesNo = input("you have chosen difficulty 1, is this correct? ")
        if yesNo.upper() == 'Y':
            level  = 1
        elif yesNo.upper() == 'N':
            level  = 4
        else:
            print ("You have entered the wrong thing")
    elif level == 2:
        yesNo = input("you have chosen difficulity 2, is this correct? ")
        if yesNo.upper() == 'Y':
            level  = 2
        elif yesNo.upper() == 'N':
            level  = 4
        else:
            print ("You have entered the wrong thing")
    elif level == 3:
        yesNo = input("you have chosen difficulity 3, is this correct? ")
        if yesNo.upper() == 'Y':
            level  = 3
        elif yesNo.upper() == 'N':
            level  = 4
        else:
            print ("You have entered the wrong thing")

return level 


def question(level):
    if level == 1:
        print ("hi")

def main():

    getName()
    difficulty()
    question(level)

我正在尝试获取变量' level'从难度函数进入问题函数,所以我可以使用它,当我运行程序时,它给我一个错误,上面写着“NameError:Name' level is not defined&#39 ;.有人可以帮帮我吗。感谢

3 个答案:

答案 0 :(得分:2)

变量Detected: x add(s)仅在两个函数的范围内定义,但不在level的范围内。您必须在main()范围内定义一个变量(称为level)才能访问它。尝试:

main()

这样,def main(): getName() level = difficulty() question(level) 可以访问difficulty()(在level内名为difficulty())返回的变量。

另外,这是您的实际代码吗?我注意到一些错误,例如main()拼写有两种不同的方式,而difficulty()内缺少缩进,如果你运行它会产生意想不到的结果。如果你有这个代码,请发布你的逐字代码,以便更容易分辨具体问题。

答案 1 :(得分:0)

您需要检索从困难函数返回的级别值

def main():
    getName()
    level = difficulty()
    question(level)

答案 2 :(得分:0)

我相信global方法可以做到这一点,它将函数中使用的局部arg转换为全局可调用的全局arg。

def difficuilty():
    level = 0
    while level >=4 or level == 0:
        level = int(input("Please enter the difficulty (1/2/3)"))
        global level

那种方式(级别)可以调用。最后一点,根据你的应用,我会选择Milo的答案,因为使用global方法可能有其缺点。