Skip to main content
 首页 » 编程设计

python之随机生成数学题

2024年10月25日11傻小

我的任务是生成一个代码来问候用户并询问他们的名字,将他们的名字存储为 username。然后生成2个随机数和一个操作。向用户提出问题。之后它会检查用户的回答是否正确,同时将 1 添加到 questionsAsked。如果正确,则将 1 添加到 correctAnswers。如果答案不正确,则会告知用户正确答案。该程序应在 10 个问题后结束(因此 while questionAsked > 11)。应向用户提供他们的 用户名 以及他们答对了多少个问题。

我的问题是当我运行代码时,出现了 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 ,我将其移出测试,现在您不再需要检查测试是否失败。

由于您从 0 开始计数,因此您想测试 < 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)) 

三个参数分别放在{}的位置按顺序出现。