如果发生ValueError,我如何打印一条消息?

问题描述 投票:0回答:1
while answers_right < 3:

    ran_number_1 = random.randint(10, 99)
    ran_number_2 = random.randint(10, 99)
    solution = ran_number_1 + ran_number_2

    print(f"What is {ran_number_1} + {ran_number_2}?")
    user_answer = int(input("Your answer: "))


    if user_answer == solution:
        answers_right += 1
        print(f"Correct. You've gotten {answers_right} correct in a row.")
    elif user_answer != solution:
        answers_right = 0
        print(f"Incorrect. The expected answer is {solution}.")


if answers_right == 3:
    print("Congratulations! You've mastered addition.")

我想添加一个额外的if语句,以防有人输入字符串并返回 "无效响应 "而不是回溯错误的消息。

valueerror
1个回答
0
投票

使用python中的异常处理可以解决你的问题,你也可以为特定的条件生成自己的错误类。

if x < 3:
      raise Exception("Sorry, no numbers below 3")

使用 throw 和 raise 关键字,你可以生成自己的错误。

更多参考此处链接


0
投票

解决这个问题的正确方法是查看回溯中的错误类型,并使用tryexcept块。它将显示类似于 TypeError: error stuff hereValueError: error stuff also here.

你做 tryexcept 的方法是:

try:
    some_code()
    that_might()
    produce_an_error()
except some_error_type:
    do_stuff()
except_some_other_error_type:
    do_other_stuff()

所以,为了捕获一个ValueError和一个TypeError,你可以这样做。

try:
    buggy_code()
except ValueError:
    print("Woah, you did something you shouldn't have")
except TypeError:
    print("Woah, you did something ELSE you shouldn't have")

如果你想要回溯,你可以在except下面添加一个单独的 "raise "语句。比如说,你可以在exception下面添加一个孤独的 "raise "语句。

try:
    buggy_code()
except ValueError:
    print("Woah, you did something you shouldn't have")
    raise
except TypeError:
    print("Woah, you did something ELSE you shouldn't have")
    raise

在现代社会,错误已经变得更加有用了。它们不会破坏整个系统了,而且有处理它们的方法。像上面这样的TryExcept块给你提供了工具,让你的代码只在特定的错误或一组错误被提出时执行。

© www.soinside.com 2019 - 2024. All rights reserved.