尝试运行此简单的python脚本时出现错误:
def ask_x():
x = int(input('What is X?'))
def ask_y():
y = int(input('What is Y?'))
def result():
print(z)
def count():
if (x>10):
z = x + y
else:
z = 0
print('nono')
#start of program
ask_x()
ask_y()
count()
result()
我正在使用Python3。我尝试搜索论坛并发现Stackoverflow - input() error - NameError: name '…' is not defined ,但它对我不起作用。
答案 0 :(得分:0)
解决范围的一种方法是从函数中返回所需的变量,并将其传递到需要的位置。我更喜欢使用全局变量:
def ask_x():
return int(input('What is X?'))
def ask_y():
return int(input('What is Y?'))
def result(z):
print(z)
def count(x,y):
if (x>10):
z = x + y
else:
z = 0
print('nono')
return z
#start of program
x = ask_x()
y = ask_y()
z = count(x,y)
result(z)
最好使用How to ask user for valid input中介绍的一种方法来获取您的输入:
def askInt(text):
"""Asks for a valid int input until succeeds."""
while True:
try:
num = int(input(text))
except ValueError:
print("Invalid. Try again.")
continue
else:
return num
x = askInt("What is X?")
y = askInt("What is Y?")
通过这种方式,您可以传入变化的值(文本),并从变量解析和验证中受益。
答案 1 :(得分:0)
这是因为您的变量在本地范围内。您无法在x
函数之外访问ask_x()
。
我建议您阅读有关函数的文章,以更好地理解这一点。
def ask_x():
return int(input('What is X?'))
def ask_y():
return int(input('What is Y?'))
def result(z):
print(z)
def count(x, y):
if (x>10):
return x + y
else:
print('nono')
return 0
#start of program
x = ask_x()
y = ask_y()
z = count(x, y)
result(z)
这将获取每个函数中的值,但是,不是将它们存储在本地范围中,而是将其返回到主函数并存储在相应的变量中。
然后,您可以将x
和y
作为参数发送到count()
,注意逻辑,然后将值存储为z
。
我希望这有道理!
答案 2 :(得分:0)
如果您不想返回,则只需使用一些默认值初始化变量
x=0
y=0
z=0
def ask_x():
global x
x = int(input('What is X?'))
def ask_y():
global y
y = int(input('What is Y?'))
def result():
global z
print(z)
def count():
global x,y,z
if (x>10):
z = x + y
else:
z = 0
print('nono')
#start of program
ask_x()
ask_y()
count()
result()
答案 3 :(得分:0)
Python遵循函数作用域,这与某些其他语言(如c遵循块作用域)不同。这意味着在函数内部定义的变量不能在外部访问。除非它们是全局定义的。
解决您的问题的方法: 您可以将它们返回到函数中并将它们存储在全局范围内的变量中,也可以将所有输入语句放入单个函数中。