繁体   English   中英

“NameError:当我尝试在 Python3 中使用该变量时,未定义名称‘响应’

[英]"NameError: name 'response' is not defined when i try to use the variable in Python3

import sys

def func2():
    print("1.Type a number ")
    print("2.Exit the program ")
    response = int(input())

func2()

def func1():
        print('Are you sure ? ') 
        print("Yes or No")
        response = input()
        if response == 'Yes':
            sys.exit()
        elif response == "yes":
            sys.exit()
        else:
            func2()

if response == 1:
    secondresponse = input("Print a number ")
    print ("You typed in "+ secondresponse+ ".")
elif response == 2:
    func1()

为什么它给我错误 NameError: name 'response' is not defined 当我在 function 中调用变量时。 或者这是不允许的?

因为响应是在 function 中定义的,所以使用全局来解决它

变量response仅在函数func1 & func2中定义:

现在,您正试图在定义变量之前访问它,因此会产生NameError Python 不知道response是什么,因为它与您的函数不在同一个 scope 中。

相反,您应该从func2()返回响应,然后检查response的值。

def func2():
    print("1.Type a number ")
    print("2.Exit the program ")
    response = int(input())
    return response 

...

if func2() == 1:
  ...

我建议您了解有关scope 的更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM