循环if语句Python

时间:2018-02-18 01:20:00

标签: python

我制作了一个Python脚本,它会产生乘法问题,如果乘法问题错误,我唯一的问题是。我需要让脚本再次显示问题并运行if语句我不需要将if语句作为函数吗?如果是这样,我该怎么做?我对python还很陌生,任何帮助都会受到赞赏!

import random 
limit = 12
number_problems = int(input('How many problems do you want to solve? '))

for i in range(number_problems):      
    x, y = random.randint(1,limit), random.randint(1,limit)
    true_ans = x*y
    print(x ,'x', y , '=' )
    ans = int(input('your answer:'))

    if ans == true_ans:
        print("correct!")
    elif ans < true_ans:
        print('Your answer is to low')
        print(x ,'x', y , '=' )
        ans = int(input('your answer:'))
    elif ans > true_ans:
        print('Your answer is to high')
        print(x ,'x', y , '=' )
        ans = int(input('your answer:'))
    else:
        print("incorrect! The answer is ", true_ans)

2 个答案:

答案 0 :(得分:0)

我对您的问题的理解是,您希望在用户正确回答之前继续提出相同的问题。你可以使用一个函数,但基本上你需要另一个循环(for循环迭代你想问的问题数量)和一个内循环继续显示问题,直到用户正确输入。

for i in range(number_problems)
   has_answered = false
   while not has_answered
      <your validation code, if valid answer, set has_answered to true>

答案 1 :(得分:-1)

使用while是达到此目的的一种方法。

以下是如何构建代码的示例。

import random 
limit = 12
number_problems = int(input('How many problems do you want to solve? '))

for i in range(number_problems):

    x, y = random.randint(1, limit), random.randint(1, limit)
    true_ans = x*y
    print(x ,' x ', y , '=' )
    ans = int(input('your answer:'))

while ans != true_ans:

    if ans < true_ans:
        print('Your answer is too low')
        print(x ,'x', y , '=' )
        ans = int(input('your answer:'))

    elif ans > true_ans:
        print('Your answer is too high')
        print(x ,'x', y , '=' )
        ans = int(input('your answer:'))

print("correct!")