简体   繁体   English

一起使用 while 循环和 try-except

[英]Use the while loop and try-except together

this is my code:这是我的代码:

while True:
    try:
        varA = int(input('enter your number'))
        varB = int(input('enter your second number'))
        break
    except ValueError:
        print('ValueError')

When varB does not run in terms of ValueError, the loop continues.当 varB 没有按照 ValueError 运行时,循环继续。 Okay, but I do not want varA to run.好的,但我不希望 varA 运行。 (I want varA to run if the varB value does not give an error.) (如果 varB 值没有给出错误,我希望 varA 运行。)

Just use 2 loops.只需使用2个循环。

while True:
    try:
        var_a = int(input("enter your number"))
        break
    except ValueError:
        print("ValueError")

while True:
    try:
        var_b = int(input("enter your second number"))
        break
    except ValueError:
        print("ValueError")

Meaning that you keep asking your first number until it does not produce any error.这意味着您不断询问您的第一个数字,直到它不会产生任何错误。 When no error occurs on your first variable, do the same with your second one.当第一个变量没有发生错误时,对第二个变量执行相同的操作。

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

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