0

I made a Python script that generates multiplication problems my only issue is if the multiplication problem is wrong. I need to get the script to display the question again and run through the if statement wouldn't I need to make the if statement a function? If so how would I do that? I'm still pretty new to python any help would be appreciated!

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)
Jake
  • 53
  • 1
  • 7
  • Here is a link to the official documentation tutorial on [how to define a function](https://docs.python.org/3/tutorial/controlflow.html#defining-functions). There must be something about loops too, somewhere. – Jongware Feb 18 '18 at 01:28
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – wwii Feb 18 '18 at 01:44

2 Answers2

0

My understanding of your question is that you want to continue to ask the same question until the user has answered correctly. You could use a function for this, but essentially you need another loop (the for loop to iterate over the number of questions you want to ask and an inner loop to continue to display the question until the user inputs correctly.

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

Using a while is one way to achieve this.

Below is an example of how you can structure your code.

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!")
jpp
  • 159,742
  • 34
  • 281
  • 339