Python问答游戏逻辑E

2024-06-24 13:52:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试练习python,因为我很快就要开始12年级了。我创造了一个问答游戏,但当我答对问题时,它总是说它错了

print("Welcome to the math quiz game!")
for i in range(0,10):
    operators = ['+','-','*','/']
    import random
    num1 = random.randint(1,10)
    num2 = random.randint(1,10)
    randop = random.choice(operators)
    question = input("What is %d %s %d: " % (num1,randop,num2))
    if randop == "+":
        answer = num1 + num2
    elif randop == "-":
        answer = num1 - num2
    elif randop == "*":
        answer = num1 * num2
    elif randop == "/":
        answer = num1 / num2
    if question == answer:
        print("\nCorrect")
    elif question != answer:
        print("Incorrect or Invalid")

Tags: thetoanswer游戏ifrandomquestionprint
2条回答

如前所述,您需要将返回值从input()转换为浮点(以处理除法中的小数):

question = float(input("What is %d %s %d: " % (num1,randop,num2)))

我不建议这样做,因为错误的输入会使游戏崩溃,所以使用带有try/except块的输入验证:

question = input("What is %d %s %d: " % (num1,randop,num2))
try:
    question = float(question)
except ValueError:
    print('Invalid or incorrect.')
    continue # skip the rest of the code and head straight into the next iteration in the for loop

另外,我不建议包含除法选项,因为大多数值都是循环小数,除非事先检查答案不会循环,或者将答案四舍五入到小数点后2位,并要求用户提供2个d.p答案,否则无法正确输入

(也可以将'answer'变量设置为字符串,而不是将'question'设置为int)

在使用==的程序中进行比较时,我们必须比较两个类型相同的变量(在启动Python时可能会有偏差)。Answer是一个数字,question是一个由用户编写的字符串。因此,Python认为这两个是不同的和错误的。要避免这种情况,您必须将数字转换为字符串或将字符串转换为数字,以便比较相同类型的两个变量。你知道吗

相关问题 更多 >