繁体   English   中英

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

您的示波器存在问题- 有关更多信息,请参见此SO答案

简而言之, check_answer函数无法“看到” blank1变量。 blank1被永远只能内部参考ask_for_input定义之前check_answer ,并在Python(和最现代的语言),这是行不通的。 功能是自私的,喜欢将所有内容都保留在其中; 您必须与他们合作才能让他们与其他功能共享。

有几种解决方案:

  1. blank1全局(但是您不应该这样做-参见此处
  2. ask_for_input内定义check_answer (我不建议这样做)
  3. 通过blank1作为参数和返回的结果input在调用ask_for_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返回时,它的堆栈帧丢失:

global
    check_answer

因此,您必须想出如何通过分配范围更广的变量(针对global的建议)或通过return来获得这些结果的方法。

blank1变量的范围仅限于ask_for_input()函数。 您需要全局声明函数定义之外的所有blank变量。

在以下行之后添加

d = total - y
blank1=''
blank2=''
blank3=''
blank4=''
blank5=''

blank1的范围以及其他空白变量只是局部变量。 您必须使它们成为全局变量。

*编辑:看来我的回复有点晚了。 其他答案是很好的解决方案。

暂无
暂无

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

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