R Nash R Nash - 11 months ago 58
Python Question

How to only make a variable decrease once before a while loop repeats (Python)

At school I have to do a mini homework of programming a quiz. In this quiz, a user has to input the answer. If they're right, they move straight onto the next question, if they're wrong, then the attempts they have left decrease by 1.
I'm using a while loop to make sure that while the amount of attempts there are left are greater than 0, every time that the user answers incorrectly, it will take off 1 attempt. However, every time I run this command, it loops completely out of control, and ends up subtracting all of the attempts left 1 by 1.
Here's what I have in one question:

answer1 = int(input("What is 420 X 15?\n"))
while trys != 0:
if answer1 == 420*15:
trys = 0 #To move straight onto the next question, sets to 0
elif answer1 != 420*15:
trys = trys - 1
print("Incorrect, "+str(trys)+" attempts left")

Running this in Python 3.5.2 Shell results in this outcome:

What is 420 X 15?
Incorrect, 2 attempts left
Incorrect, 1 attempts left
Incorrect, 0 attempts left

Then it moves onto the next question.

The '1' on line 2 is what I answered purposefully to get the answer wrong. I assume this error definitely has something to do with the loop repeating the
trys = trys - 1
part of the code on line 7. When the user get's the answer right, there's no problem with the code and it moves onto the next question as I hoped for. When the user is incorrect, it just loops out of control.

Any help would be greatly appreciated, or a redirection to another thread with the answer I'm looking for :)

Answer Source

You should move the input inside the loop:

while trys != 0:
    answer1 = int(input("What is 420 X 15?\n"))
    # ...