有没有办法在除块之外打印自然错误消息?

发布于 2025-02-12 00:27:31 字数 598 浏览 2 评论 0原文

我正在练习错误处理,我有一个问题。您可以做到吗

try:
    a = int(input('Please enter the first number it must be >= 200' + '\n' + '(note the sum of both numbers must be <=300)'))
    b= int(input('please your second number it must be <= 50'))
    c = a + b
    assert a >=200 and isinstance(a, int), 'invalid entry for a must be <= 200 and a number'
    assert b<=50 and isinstance(b, int), 'invalid entry for b must be <=50 and a number'
    assert c <= 300, 'The sum of your numbers is >300'
except ValueError
    print('error')
else:
    print('All in range')

I am practicing with error handling and I have a question. can you make it so the error messages in the assert will be displayed in the except block right now if a error occurs only 'error' is printed and not the actual error message

try:
    a = int(input('Please enter the first number it must be >= 200' + '\n' + '(note the sum of both numbers must be <=300)'))
    b= int(input('please your second number it must be <= 50'))
    c = a + b
    assert a >=200 and isinstance(a, int), 'invalid entry for a must be <= 200 and a number'
    assert b<=50 and isinstance(b, int), 'invalid entry for b must be <=50 and a number'
    assert c <= 300, 'The sum of your numbers is >300'
except ValueError
    print('error')
else:
    print('All in range')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

征棹 2025-02-19 00:27:32

添加一个除外的,该 sossertionError 并打印出来:

except AssertionError as e:
    print(e.args[0] if e.args else "error")

Add an except that catches the AssertionError and prints it:

except AssertionError as e:
    print(e.args[0] if e.args else "error")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文