简体   繁体   English

虽然循环不会在 Python 中退出

[英]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 循环中的 try 和 except 语句,它在第一部分工作正常,但由于某种原因它不会继续到下一个循环,在那里我要求用户选择一个数学运算符,然后代码从头开始并再次重复整个过程。

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.当代码运行时,它要求用户输入一个按预期工作的值,在输入两个值后,代码继续运行,但不是到第二个 while 循环,而是到代码的开头。 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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