繁体   English   中英

Python发生异常时如何重新运行循环?

[英]How to re-run through loop when exception happens in Python?

执行此操作时,它仅运行初始 if elif 语句。 如果我达到 0,它会在我减去数字时返回正确的打印语句。 但是,如果我尝试减去以达到负数并因此达到异常,它不会打印下面的语句并像我想要的那样重新循环。

number = 15
print("Subtract the number", number, "until it has reached 0")
while number != 0:
    try:
        x = int(input())
        number = number-x
        if number > 0:
            print("You have", number, "points to spend!")
        elif number == 0:
            print("You have used all your points!")
            break
    except number < 0:
            print("You don't have enough points for that!")
            continue

except用于捕获错误。 你要这个:

while number != 0:
    x = int(input())
    if number - x > 0:
        number -= x
        print("You have", number, "points to spend!")
    elif number == x:
        number = 0
        print("You have used all your points!")
        break
    else:
        print("You don't have enough points for that!")

暂无
暂无

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

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