gpt4 book ai didi

python - Python 3.6 中的名称错误

转载 作者:行者123 更新时间:2023-12-01 03:09:31 25 4
gpt4 key购买 nike

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

#!/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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com