如果我得到了正确的答案,它会打印一些东西,我该怎么做呢

2024-06-16 10:26:33 发布

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

import random
from browser import timer
operators = ['*', '/', '+', '-']
number = input('How many problems would you like?')
number = int(number)
counter = 1

while counter <= number:
    first = random.randint(0,10)
    second = random.randint(0,10)
    randoperator = random.choice(operators)
    problem = '{} {} {} {}'.format(first, randoperator, second, "=  ")
    answer = input(problem)
    correct = problem
    counter+=1

我试过把这个放进去,但什么都没用

if problem == answer:
            print("Correct!")

Tags: answerfromimportbrowsernumberinputcounterrandom
1条回答
网友
1楼 · 发布于 2024-06-16 10:26:33

你需要做实际的计算来找出答案。下面是一个快速而肮脏的方法:

import random
operators = ['*', '/', '+', '-']
number = input('How many problems would you like?')
number = int(number)
counter = 1

while counter <= number:
    first = random.randint(0,10)
    second = random.randint(0,10)
    randoperator = random.choice(operators)
    problem = '{} {} {}'.format(first, randoperator, second)
    answer = input(problem + ' =  ')
    if eval(problem) == float(answer):
        print("Correct!")
    counter+=1

使用eval并不是一个好主意,因为this question.的答案中列出了一些原因。在您的例子中,您已经知道两个整数和运算符,因此在不使用eval的情况下查找预期答案非常容易。假设您定义了一个可以为您执行此操作的函数:

def arithmetic(op, a, b):
    if op == "+":
        return a + b
    elif op == "-":
        return a - b
    elif op == "*":
        return a * b
    elif op == "/":
        return a / b

然后调用此函数以获得预期答案,并将其与用户给出的答案进行比较

while counter <= number:
    first = random.randint(0,10)
    second = random.randint(0,10)
    randoperator = random.choice(operators)
    problem = '{} {} {}'.format(first, randoperator, second)
    answer = input(problem + ' =  ')
    if arithmetic(randoperator, first, second) == float(answer):
        print("Correct!")
    counter+=1

相关问题 更多 >