简体   繁体   English

如何使用 Try 和 Exception 在 Python 中引发带有打印消息的错误?

[英]How do I use a Try and Exception to raise an error with a print message in Python?

I'm trying to run a collatz in Python and I'm having trouble taking into account input that isn't an integer.我正在尝试在 Python 中运行 collat​​z,但在考虑不是整数的输入时遇到问题。 I would like to have a Try and Except to work within my code that considers the user's non-integer input.我想在考虑用户非整数输入的代码中使用 Try and except 。 Please see my code below.请在下面查看我的代码。

number = int(input("Please enter a number: "))

def collatz(number):
    if number % 2 == 0:
        print(number // 2)
        return number // 2
    elif number % 2 == 1:
        print(number * 3 + 1)
        return number * 3 + 1

while number != 1:
    try:
        number = collatz(int(number))
    except ValueError:
        print("Something went wrong, please try again...")

You are not using the try except when you are calling int on the input, which is why it is still erroring.除非在输入上调用 int ,否则您没有使用 try ,这就是它仍然出错的原因。 You should use 2 while loops like this:您应该像这样使用 2 个 while 循环:

number = input("Please enter a number: ")
while not number.isdigit():
    number = input("Please enter a number again: ")
number = int(number)

def collatz(number):
    if number % 2 == 0:
        print(number // 2)
        return number // 2
    elif number % 2 == 1:
        print(number * 3 + 1)
        return number * 3 + 1

With try-except (in this case don't include the initial stuff in the other solution):使用 try-except(在这种情况下,不要在其他解决方案中包含初始内容):

while True:
    try:
        number = int(input("Please enter a number: "))
        break
    except:
        pass

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

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