【问题标题】:How do you go to the beginning of an if statement in the else section? Python 3.2您如何转到 else 部分中 if 语句的开头?蟒蛇 3.2
【发布时间】:2016-12-20 03:10:28
【问题描述】:

问题就在标题中:如何跳转到 else 部分中 if 语句的开头?

代码:

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

【问题讨论】:

  • 听起来你需要loop
  • 我通常在这种情况下使用循环。如果输入有效,则继续。其他循环。我不认为你可以像 c 中的 goto 那样在 python 中跳转语句

标签: python python-3.x python-3.2


【解决方案1】:

循环运行,在输入满足条件之前永不中断。

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

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

如果您输入的值无法转换为int 并终止程序,此代码将引发异常。

要解决这个问题,请捕获异常并继续。

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.') 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-30
    • 2018-10-04
    • 2019-04-09
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    相关资源
    最近更新 更多