python - Python 3.6 中的名称错误

标签 python python-3.x nameerror

我是编码新手,正在研究一个简单的数学项目。 我有以下代码:

#!/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 函数内调用该函数时,会导致错误。我不能在另一个函数中调用一个函数吗? 请帮忙!谢谢。

最佳答案

我认为解决此问题的最佳方法是修复您的 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返回时,它的堆栈帧丢失:

global
    check_answer

因此,您必须弄清楚如何获取这些结果,要么通过分配给更广泛范围内的变量(对于global的建议),要么通过return .

关于python - Python 3.6 中的名称错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42992240/

相关文章:

c++ - Python C头文件解析及逆向初始化

python - 使用python将十六进制字符串转换为整数

python - 将 TXT 加载到 postgres 数据库中,将不存在的列填充为 null

python - 使用朴素贝叶斯的文本微调器

python:如何从列表中打印单独的行?

python - Python中有什么函数可以聚合秒级毫秒数据吗?

python - wxPython 无法与 Python 3.7 一起使用(在 Windows 7,64 位上)?

Python:NameError:未定义全局名称 'foobar'

python 名称错误: global name is not defined

python - 尝试使用 mido 的 get_output_names 时出现 NameError