输入负数时,如何向用户打印消息?

发布于 2025-02-03 09:22:43 字数 375 浏览 1 评论 0原文

我正在学习尝试现在,语句现在,我希望该程序在插入负数时打印出一条消息,但我不知道如何创建该输出的语句顺序:

print("how many dogs do you have?")
numDogs= input()
try:
    if int(numDogs)>=4:
        print("that is a lof of dogs")
    else:
        print("that is not that many dogs")
except:
    print("you did not enter a number")

我希望该程序在用户输入负数时打印TJE输出。 我该怎么做?

I am learning about the try and except statements now and I want the program to print out a message when a negative number is inserted but I don't know how to create the order of the statements for this output:

print("how many dogs do you have?")
numDogs= input()
try:
    if int(numDogs)>=4:
        print("that is a lof of dogs")
    else:
        print("that is not that many dogs")
except:
    print("you did not enter a number")

I want the program to print tje output when the user enters a negative number.
How can I do it?

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

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

发布评论

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

评论(3

葬﹪忆之殇 2025-02-10 09:22:43

只是代码就像
尝试:
如果没有< 0:
打印(“否是负面”),

    raise error 

而进一步的代码将是

Just code is like
try:
if no<0:
print("no is negative ")

    raise error 

And further code will be as it is

毁我热情 2025-02-10 09:22:43

这是您要实现的目标。

class CustomError(Exception):
    pass

print("how many dogs do you have?")

try:
    numDogs = int(input())
    if numDogs < 0:
        raise CustomError
    elif int(numDogs)>=4:
        print("that is a lot of dogs")
    else:
        print("that is not that many dogs")
except CustomError:
    print("No Negative Dogs")
except:
    print("you did not enter a number") 

您可以首先创建自定义异常。参见 https://www.programiz.com/python-programiz.com/python-programming/python-programming/user-programming/user-defined - 外观

之后,您应该有一个条件以首先检测负值,然后从中引起错误。

最后,您可以创建多个异常以获取不同的错误。第一个因负值输入(就像您的状况对您所做的那样)提出了第一个,而第二个则用于捕获非有效值(例如字符)。

请注意,您的int(输入)段应在您的尝试块中以检测错误

Here is what you are trying to achieve.

class CustomError(Exception):
    pass

print("how many dogs do you have?")

try:
    numDogs = int(input())
    if numDogs < 0:
        raise CustomError
    elif int(numDogs)>=4:
        print("that is a lot of dogs")
    else:
        print("that is not that many dogs")
except CustomError:
    print("No Negative Dogs")
except:
    print("you did not enter a number") 

You can start by creating a custom exception. See https://www.programiz.com/python-programming/user-defined-exception

After which, you should have a condition to first detect the negative value then raise an error from it.

Finally, You can then create multiple excepts to get different error. The first except is raised on input of negative values (as your condition will do for you) whereas the second is used to catch non valid value such as characters.

Note that your int(input) segment should be WITHIN your try block to detect the error

逆光下的微笑 2025-02-10 09:22:43

我发现的解决方案来自这个问题

我希望该程序在插入负数时打印出消息

您可以像 @Jackson的答案那样提出一个值,或者您可以在下面的代码中提出例外。

    elif numDogs < 0:
        raise Exception("\n\n\nYou entered a negative number")


    def main():
        
        try:
            numDogs= int(input("how many dogs do you have?  "))
            if numDogs >= 4:
                print("that is a lot of dogs")
            elif numDogs < 0:
                raise Exception("\n\n\nYou entered a negative number")
            else:
                print("that is not that many dogs")
        except ValueError:
            print("you did not enter a number")  
    main() 

我应该指出的一件事是,只要检查这个数字是否是&lt,就可以更好地练习。 0或NAN。但是,就像您说的那样,您正在尝试了解尝试和语句以外的尝试。 很酷


    try:
        if numDogs < 0:
            raise ValueError
    except ValueError:
        print("Not a negative Number")

我认为在此代码段中,您可以丢下想要的错误,并且尝试会捕获它 。猜猜我也在学习很多。只有一部分是,如果发生这种情况,如果您的代码不知道它是一个负数问题,或者数字是否类似于“ A”,它不能转换为一个(以此方式)。

总而言之,我认为最好解决此问题,没有尝试 /除了语句以外:



    def main():
        
        num_dogs = input("# of dogs: ")
        if not num_dogs.isnumeric():
            return "Error: NAN (not a number)"
    
        num_dogs = int(num_dogs)
    
        return ["thats not a lot of dogs", "that's a lot of dogs!"][num_dogs >= 4] if num_dogs > 0 else "You Entered a negative amount for # of dogs"
    
    
    print(main())

Notice that I wrapped everything in a `main` function, because that way we can return a string with the result; this is important because if we get an error we want to break out of the function, which is what return does.

Solution I found is from this SO question

I want the program to print out a message when a negative number is inserted

You can raise a valueError like @Jackson's answer, or you can raise an Exception like in my code below.

    elif numDogs < 0:
        raise Exception("\n\n\nYou entered a negative number")


    def main():
        
        try:
            numDogs= int(input("how many dogs do you have?  "))
            if numDogs >= 4:
                print("that is a lot of dogs")
            elif numDogs < 0:
                raise Exception("\n\n\nYou entered a negative number")
            else:
                print("that is not that many dogs")
        except ValueError:
            print("you did not enter a number")  
    main() 

One thing that I though I should point out is that its probably better practice to just check if the number is < 0 or is NAN. But like you said, you're trying to learn about the try and except statements. I thought it was cool that in this code segment:


    try:
        if numDogs < 0:
            raise ValueError
    except ValueError:
        print("Not a negative Number")

you can throw what error you want and your try will catch it. Guess im still learning a lot too. Only part is, if that happens if your code then one won't know if its a negative number issue or if the number is something like "a", which cannot be converted to one (in this way).

All in all, I think its best to solve this problem with no try / except statements:



    def main():
        
        num_dogs = input("# of dogs: ")
        if not num_dogs.isnumeric():
            return "Error: NAN (not a number)"
    
        num_dogs = int(num_dogs)
    
        return ["thats not a lot of dogs", "that's a lot of dogs!"][num_dogs >= 4] if num_dogs > 0 else "You Entered a negative amount for # of dogs"
    
    
    print(main())

Notice that I wrapped everything in a `main` function, because that way we can return a string with the result; this is important because if we get an error we want to break out of the function, which is what return does.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文