Python 3.6 中的名称错误
Name Error in Python 3.6
我是编码新手,正在做一个简单的数学项目。
我有以下代码:
#!/usr/bin/env python3
import sys; print(sys.version)
import random
##Creates values to use to make random equation.
x = random.randint(1,11)
y = random.randint(1,11)
if x > y:
total = random.randint(x, 20)
else:
total = random.randint(y, 20)
##Creates actual values for A,B,C, and D in equation A+B=C+D
a = x
b = total - a
c = y
d = total - y
##Prints option choices and asks for user input
def start_game_message():
print ("Please fill in the blanks to make the following equation true:")
print ("__+__=__+__")
print ("The option choices are:" + str(a) + ", " + str(b) + ", " + str(c) + ", " + str(d))
def ask_for_input():
blank1 = input("What is the value of the first blank?")
blank2 = input("What is the value of the second blank?")
blank3 = input("What is the value of the third blank?")
blank4 = input("What is the value of the fourth blank?")
start_game_message()
##Check if user input is correct
def check_answer():
ask_for_input()
print (blank1)
if int(blank1)+ int(blank2) == int(blank3) + int(blank4):
print ("That is correct!")
else:
print ("That is incorrect. Please try again.")
ask_for_input()
check_answer()
当 运行 出现以下错误时:
Traceback (most recent call last):
File "C:/Users/duncs/PycharmProjects/moms_app/main", line 42, in <module>
check_answer()
File "C:/Users/duncs/PycharmProjects/moms_app/main", line 36, in check_answer
print (blank1)
NameError: name 'blank1' is not defined
我是不是做错了什么?我为每个应该存储的空白输入值。如果我将 print(blank1) 放在 ask_for_inputs 函数中,它会打印得很好。但是当我稍后在 check_answers 函数内部调用该函数时,它会导致错误。我不能在另一个函数中调用一个函数吗?
请帮忙!谢谢。
blank1 变量的范围仅限于 ask_for_input() 函数。您需要在函数定义之外全局声明所有 blank
变量。
在下一行之后添加
d = total - y
blank1=''
blank2=''
blank3=''
blank4=''
blank5=''
您的示波器有问题 — 请参阅 this SO answer for more。
简而言之,check_answer
函数不能 "see" blank1
变量。 blank1
仅在您定义 check_answer
之前在 ask_for_input
中被引用,而在 Python(以及大多数现代语言)中这不起作用。函数是自私的,喜欢把里面的所有东西都据为己有;您必须与他们合作才能让他们与其他功能共享。
有几个解决方案:
- 使
blank1
全局化(但是你不应该 这样做 — 参见 here)
- 在
ask_for_input
里面定义check_answer
(我不推荐这个)
- 将
blank1
作为 参数 和 return ask_for_input
中 input
调用的结果返回给调用者这样你就可以将用户输入从 ask_for_input
穿出并穿入 check_answer
我个人建议选择 3。如果需要,我可以用更具体的例子来详细说明。
我认为解决这个问题的最佳方法是修复您的 ask_for_input()
:
def ask_for_input(which):
return input("What is the value of the %s blank?" % which)
start_game_message()
##Check if user input is correct
def check_answer():
inputs = []
for blank in ['first', 'second', 'third', 'fourth']:
inputs.append(ask_for_input(blank))
if int(inputs[0])+ int(inputs[1]) == int(inputs[2]) + int(inputs[3]):
print ("That is correct!")
else:
print ("That is incorrect. Please try again.")
ask_for_input()
check_answer()
这通过 return
传回结果避免了范围问题。它还减少了代码重复并利用 list
来存储 4 个输入。
至于为什么您的代码不起作用,这是因为如果您检查堆栈,您会看到:
global
check_answer
ask_for_input
-blank1
-blank2
-blank3
-blank4
当ask_for_input
returns时,栈帧丢失:
global
check_answer
所以你必须弄清楚如何得到这些结果,要么通过分配给范围更广的变量(global
的建议),要么通过 return
.
blank1的作用域,以及其他空白变量,都只是局部变量。你必须让它们成为全局变量。
*编辑:看来我的回复有点晚了。其他答案都是很好的解决方案。
我是编码新手,正在做一个简单的数学项目。 我有以下代码:
#!/usr/bin/env python3
import sys; print(sys.version)
import random
##Creates values to use to make random equation.
x = random.randint(1,11)
y = random.randint(1,11)
if x > y:
total = random.randint(x, 20)
else:
total = random.randint(y, 20)
##Creates actual values for A,B,C, and D in equation A+B=C+D
a = x
b = total - a
c = y
d = total - y
##Prints option choices and asks for user input
def start_game_message():
print ("Please fill in the blanks to make the following equation true:")
print ("__+__=__+__")
print ("The option choices are:" + str(a) + ", " + str(b) + ", " + str(c) + ", " + str(d))
def ask_for_input():
blank1 = input("What is the value of the first blank?")
blank2 = input("What is the value of the second blank?")
blank3 = input("What is the value of the third blank?")
blank4 = input("What is the value of the fourth blank?")
start_game_message()
##Check if user input is correct
def check_answer():
ask_for_input()
print (blank1)
if int(blank1)+ int(blank2) == int(blank3) + int(blank4):
print ("That is correct!")
else:
print ("That is incorrect. Please try again.")
ask_for_input()
check_answer()
当 运行 出现以下错误时:
Traceback (most recent call last):
File "C:/Users/duncs/PycharmProjects/moms_app/main", line 42, in <module>
check_answer()
File "C:/Users/duncs/PycharmProjects/moms_app/main", line 36, in check_answer
print (blank1)
NameError: name 'blank1' is not defined
我是不是做错了什么?我为每个应该存储的空白输入值。如果我将 print(blank1) 放在 ask_for_inputs 函数中,它会打印得很好。但是当我稍后在 check_answers 函数内部调用该函数时,它会导致错误。我不能在另一个函数中调用一个函数吗? 请帮忙!谢谢。
blank1 变量的范围仅限于 ask_for_input() 函数。您需要在函数定义之外全局声明所有 blank
变量。
在下一行之后添加
d = total - y
blank1=''
blank2=''
blank3=''
blank4=''
blank5=''
您的示波器有问题 — 请参阅 this SO answer for more。
简而言之,check_answer
函数不能 "see" blank1
变量。 blank1
仅在您定义 check_answer
之前在 ask_for_input
中被引用,而在 Python(以及大多数现代语言)中这不起作用。函数是自私的,喜欢把里面的所有东西都据为己有;您必须与他们合作才能让他们与其他功能共享。
有几个解决方案:
- 使
blank1
全局化(但是你不应该 这样做 — 参见 here) - 在
ask_for_input
里面定义check_answer
(我不推荐这个) - 将
blank1
作为 参数 和 returnask_for_input
中input
调用的结果返回给调用者这样你就可以将用户输入从ask_for_input
穿出并穿入check_answer
我个人建议选择 3。如果需要,我可以用更具体的例子来详细说明。
我认为解决这个问题的最佳方法是修复您的 ask_for_input()
:
def ask_for_input(which):
return input("What is the value of the %s blank?" % which)
start_game_message()
##Check if user input is correct
def check_answer():
inputs = []
for blank in ['first', 'second', 'third', 'fourth']:
inputs.append(ask_for_input(blank))
if int(inputs[0])+ int(inputs[1]) == int(inputs[2]) + int(inputs[3]):
print ("That is correct!")
else:
print ("That is incorrect. Please try again.")
ask_for_input()
check_answer()
这通过 return
传回结果避免了范围问题。它还减少了代码重复并利用 list
来存储 4 个输入。
至于为什么您的代码不起作用,这是因为如果您检查堆栈,您会看到:
global
check_answer
ask_for_input
-blank1
-blank2
-blank3
-blank4
当ask_for_input
returns时,栈帧丢失:
global
check_answer
所以你必须弄清楚如何得到这些结果,要么通过分配给范围更广的变量(global
的建议),要么通过 return
.
blank1的作用域,以及其他空白变量,都只是局部变量。你必须让它们成为全局变量。
*编辑:看来我的回复有点晚了。其他答案都是很好的解决方案。