Skip to main content
 首页 » 编程设计

python之python中函数之间的通信

2024年10月24日8mq0036

我正在做一个学校项目,我需要一些功能间沟通方面的帮助。这是我到目前为止得到的

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定义'。有人可以帮帮我吗。谢谢

请您参考如下方法:

变量level 只定义在你的两个函数的范围内,而不是在main() 的范围内。您必须在 main() 范围内定义一个变量(称为 level)才能访问它。尝试:

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

这样,从 difficulty() 返回的变量(在 difficulty() 中命名为 level)对于 是可访问的主()。

此外,这是您的实际代码吗?我注意到一些错误,比如 difficulty() 被两种不同的拼写方式,以及 difficuilty() 中缺少缩进,如果您运行它,将会产生意想不到的结果。如果您有逐字代码,请发布它,以便更容易判断具体问题是什么。