简体   繁体   中英

While loop won't exit in Python

The code below shows my try and except statement in a while loop, it works fine in the first part, but for some reason it won't continue on to the next loop, where I ask the user to pick a mathematical operator, and the code starts over at the beginning and repeats the whole process again.

while True:
        try:
            num1=float(input("Please enter a value in Number form, with 5 decimal places max"))       
            num2=float(input("And your second value in Number form, with 5 decimal places max"))
            break
        except ValueError:
            print("Incorrect, try again")

            while True:
                try:
                    userOp=input("Press 1 for Addition, 2 for Subtraction, 3 for Multiplication and 4 for Division")
                    break

When the code runs, it asks the user to enter a value which works as intended, and after inputting two values the code continues on, but not to the second while loop, but rather to the beginning of the code. How would I "exit" out of the first loop and onto the next?

this will solve your problem

while True:
    try:
        num1 = float(input("Please enter a value in Number form, with 5 decimal places max"))       
        num2 = float(input("And your second value in Number form, with 5 decimal places max"))
        break
    except ValueError:
        print("Incorrect, try again")

while True:
    try:
        userOp = int(input("Press 1 for Addition, 2 for Subtraction, 3 for Multiplication and 4 for Division"))
        break
    except ValueError:
        print('Try again')

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