首页 > 解决方案 > 如何使用 try 函数处理 python 中的特定整数异常。如何处理多个除了尝试功能

问题描述

此代码应准确说明用户正在犯什么错误并提示重试。

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

会不会有更简单的解决方案,比如 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")

标签: pythontry-except

解决方案


如果必须使用该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

推荐阅读