如何重复输入直到给出合适的答案?

2024-04-28 09:40:24 发布

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

我已经完成了一个代码,这样它就要求用户回答一个算术问题,并告诉他们答案是否正确,等等。。。。我开始做一些测试,并意识到如果用户输入任何东西,那么一个数字就会给我一个错误。 我的代码:

import random

    name=input("Welcome to this Arithmetic quiz,please enter your name:")

    score = 0

    for i in range(10):

          number1=random.randint(20,50)

          number2=random.randint(1,20)

          oper=random.choice('+-*')

          correct_answer = eval(str(number1)+oper+str(number2))

          answer = (int(input('What is:'+str(number1)+oper+str(number2)+'=')) == correct_answer)

          if answer:
                  print('Correct!')

                  score += 1

          else:
                  print('Incorrect!')

    print(name,"You got",score,"out of 10")

    if score>1 and score<=3 :
                  print('Practice More!')

    elif score>4 and score<=7 :
                  print('You did well!')

    elif score>7 and score<=9 :
                  print('Excellent!')

    elif score==10 :
                  print('You are a Genius!')

    else:
                  print('Have you tried your best?')

我想知道如何重复第9行直到用户输入一个数字? 这不是重复的,因为我希望用户明确地输入一个数字。如果他/她这么做了,他/她会告诉他们这是错的还是对的,然后继续下一个问题。在


Tags: and代码用户answernameyou数字random