简体   繁体   中英

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:
        print("Correct!")
        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?
1
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 :)

You should move the input inside the loop:

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

You should make your input inside the loop so each time it take from the user the input and check if trys reach zero so the work code should be like this for the question

trys = 3
while trys != 0:
    answer1 = int(input("What is 420 X 15?\n"))
    if answer1 == 420*15:
        print("Correct!")
        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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM