错误处理练习+处理浮点数问题

发布于 2025-01-27 01:25:40 字数 746 浏览 2 评论 0原文

上下文:在练习错误处理(在Python中),我被要求使用 为了向用户询问,“尝试语句”和“除句” 小数号的输入,然后必须将其转换为浮动 点值。

- 如果发生错误,我必须打印自己的错误消息(在这种情况下,“不是小数值!”)。 - 我还必须打印官方的Python错误消息。 - 我必须包括一个其他子句,然后确认已输入有效的十进制。

我将包括我能够提出的内容:

    error = False
    try:
        number = float(input("\nEnter an decimal value (e.g, 1.3): "))
    except ValueError as errorMsg:
        error = True
        print("\nNot an decimal.")
        print("\nPython exception:", errorMsg)
    else:
        print("you have entered a valid decimal")

当我输入实际的小数点值时,以及当我像字母字符一样输入非数值时,这似乎都起作用。我遇到了我进入普通整数(1,2,3等)的问题,其中表明没有错误,并且我输入了小数点或浮点值。 我已经尝试了多种编码方式,并最终取得了相同的结果,现在我处于停滞状态,由于知识差距,这可能是一个简单的解决方案或错误,因此,如果有人拥有一个人,我将不胜感激解决方案或建议,以便我可以解决此问题。非常感谢!

context: In a exercise about error-handling(in python), I have been asked to use
the 'try statement' and 'except clause' in order to ask the user for
input of a decimal number, which then must be converted to a floating
point value.

-I must print my own error message if an error occurs (in this case "not an decimal value!").
-I must also print the official python error message.
-I have to include an else clause to then confirm that a valid decimal has been input.

I will include what I've been able to come up with so far below:

    error = False
    try:
        number = float(input("\nEnter an decimal value (e.g, 1.3): "))
    except ValueError as errorMsg:
        error = True
        print("\nNot an decimal.")
        print("\nPython exception:", errorMsg)
    else:
        print("you have entered a valid decimal")

This seems to work both when I enter an actual decimal value, and when I enter a non numerical value like an alphabetical character. I run into my problem where I have entered a normal integer (1,2,3 etc.), where it indicates that there is no error and that I have entered a decimal or floating point value.
I have tried multiple ways of coding this and have ended up with the same result and I am now at a standstill, annoyingly it is probably a simple solution or an error on my behalf due to knowledge gaps, so I would appreciate if anybody has a solution or suggestion so I can fix this issue. Many thanks!

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文