如何使用 try 函数处理 python 中的特定整数异常。如何处理多个除了 try 函数

How to handle specific integer exception in python with try function. How to handle multiple except with try function

这段代码应该准确地告诉用户犯了什么错误并提示重试。

如何为每个错误制作自定义错误消息?

是否有像 c 语言编程中的 do-while 这样更简单的解决方案?

while True:
    height = int(input("Height: "))
    try:
        check_answer = int(height)
        assert (int(height) > 0)
        assert (int(height) < 9)
        break
    except ValueError:
        print("must enter a number")
    except (???):
        print("enter a number greater than 0")
    except (???):
        print("enter a number smaller than 9")

如果必须使用 assert 语句,可以将消息作为第二个参数传递,使其成为 AssertionError 异常的消息:

while True:
    try:
        height = int(input("Height: "))
        assert height > 0, "enter a number greater than 0"
        assert height < 9, "enter a number smaller than 9"
        break
    except ValueError:
        print("must enter a number")
    except AssertionError as e:
        print(str(e))

但是您想要实现的目标通常是使用简单的 if 语句来代替:

while True:
    try:
        height = int(input("Height: "))
    except ValueError:
        print("must enter a number")
    if height <= 0:
        print("enter a number greater than 0")
    elif height >= 9:
        print("enter a number smaller than 9")
    else:
        break