简体   繁体   English

您如何转到else节中if语句的开头? Python 3.2

[英]How do you go to the beginning of an if statement in the else section? Python 3.2

The question is in the title: How do you go to the beginning of an if statement in the else section? 问题在标题中:您如何进入else节中if语句的开头?

Code: 码:

p1 = int(input())
if p1 <= 9 and p1 >= 1:
    pass
else:
    print('Invalid input. Please try again.')
    p1 = input()

Run in a loop and never break out until the input meets the criteria. 循环运行,直到输入满足条件时才中断。

while True:
    p1 = int(input("input something: "))
    if p1 <= 9 and p1 >= 1:
        break

    print('ERROR 404. Invalid input. Please try again.')

This code will throw an exception if you enter a value that cannot be converted to an int and terminate the program. 如果输入的值无法转换为int并终止程序,则此代码将引发异常。

To get around this catch the exception and carry on. 为了解决这个问题,请捕获异常并继续。

while True:
    try:
        p1 = int(input("input something: "))

        if p1 <= 9 and p1 >= 1:
            break
    except ValueError:
        pass

    print('ERROR 404. Invalid input. Please try again.') 

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

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