我的任务是生成一个代码,用于问候用户并询问他们的名称,将其名称存储为username
。然后生成2个随机数和一个操作。问题是向用户询问的。之后,它会检查用户的回答是否正确,同时将1
添加到questionsAsked
。如果正确,1
会添加到correctAnswers
。如果不正确,用户会被告知正确答案。该计划应在10个问题后结束(因此while questionAsked > 11
)。应该向用户提供他们的username
以及他们纠正了多少问题。
我的问题是当我运行代码时,它会出现NameError: name 'questionAsked' is not defined
。我正在努力弄清楚我还能如何定义questionAsked
。
这是我到目前为止所做的:
import random
import math
def test():
Username=input("What is your name?")
print ("Welcome"+Username+" to the Arithmetic quiz")
num1=random.randint(1, 10)
num2=random.randint(1, 10)
Ops = ['+','-','*']
Operation = random.choice(ops)
num3=int(eval(str(num1) + operation + str(num2)))
print("What is" +" "+str(num1) + operation +str (num2,"?"))
userAnswer= int(input("Your answer:"))
if userAnswer != num3:
print("Incorrect. The right answer is"+" "+(num3))
return False
else:
print("correct")
return True
correctAnswers=0
questionsAsked=0
while questionAsked > 11:
if test () == True:
questionsAnswered +=1
correctAnswers +=1
if test () == False:
questionsAnswered +=1
答案 0 :(得分:2)
您有一个测试while questionAsked > 11
,但不要在代码中的任何其他地方使用该名称。你当然没有定义它。您可能想要测试 questionsAsked
(使用s
)。
然而,还有其他问题。当你提出少于的11个问题时,循环应该继续,而不是更多。你也可以两次调用test()
,每次循环只调用一次。在你的循环中,你使用 questionsAnswered
,但从未定义过,并且不会增加questionsAsked
;你可能想要增加后者:
correctAnswers=0
questionsAsked=0
while questionsAsked < 10:
if test():
correctAnswers +=1
questionsAsked +=1
现在test()
只被称为一次。你的分支都增加questionsAsked
,我把它移出了测试,现在你不再需要检查测试是否失败了。
由于您从零开始计算,您想要测试< 10
,而不是11
。
您可以使用while
函数使用for
循环,而不是range()
循环:
for question_number in range(10):
if test():
correctAnswers +=1
现在for
循环负责计算所询问的问题数量,您不再需要手动增加变量。
接下来,您需要移动username
功能的test()
处理 。您不需要每次都询问用户的姓名。在循环之前询问一次名称,以便在10个问题之后访问用户名:
def test():
num1=random.randint(1, 10)
num2=random.randint(1, 10)
# ... etc.
Username = input("What is your name?")
print("Welcome", Username, "to the Arithmetic quiz")
correctAnswers = 0
for question_number in range(10):
if test():
correctAnswers +=1
# print the username and correctAnswers
您也需要在test()
函数中注意您的名字;您可以定义名称Ops
和Operation
,但请尝试将其用作ops
和operation
。这不起作用,你需要在任何地方使用相同的情况来引用这些名称。 Python style guide建议您使用全部小写和下划线表示本地名称,以区别于类名(使用CamelCase,初始大写字母和单词之间没有空格)。
下一个问题:您在str()
使用了两个参数:
print("What is" +" "+str(num1) + operation +str (num2,"?"))
这不起作用;两个参数str()
调用用于将字节解码为Unicode字符串。
不要使用字符串连接,只需将值作为单独的参数传递给print()
。该函数将负责将事物转换为字符串,并在不同的参数之间为您添加空格:
print("What is", num1, operation, num2, "?")
现在num2
和"?"
之间会有一个空格,但这不是一个大问题。您可以使用str.format()
method创建一个包含占位符的字符串,其中为您填充方法的参数,再次自动转换为字符串。这允许您更直接地控制空间:
print("What is {} {} {}?".format(num1, operation, num2))
这三个参数按顺序放置在每个{}
出现的位置。
答案 1 :(得分:0)
您在变量名称和缩进中存在许多差异。记住Python区分大小写。顺便说一下,你的while循环中的条件会导致你的程序不问任何问题。
例如,您创建了一个名为Ops
的操作列表,然后使用随机模块从ops
中选择一个操作。 Python将不可避免地抛出错误,因为ops
实际上并未定义。相反,您应该使用Ops
,因为这是您实际声明的变量,带有大写字母。同样,Python区分大小写。
同样,Python识别questionAsked
和questionsAsked
之间的差异。它是一个或另一个,所以选择一个名称并保持一致。