我的任务是生成一个向用户打招呼的代码,并询问他们的姓名,并将其姓名存储为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
最佳答案
您有一个测试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))
三个参数按顺序放置在每个
{}
出现的位置。