【问题标题】:Python 3 - Error handling to calculatorPython 3 - 计算器的错误处理
【发布时间】:2015-11-10 18:25:50
【问题描述】:

出于培训目的,我正在使用 Python 3 做一个简单的计算器。

这就是我现在所处的位置:

import math
number1 = int(input("Give the first number: "))
number2 = int(input("Give the second number: "))

while True:
     print("(1) +\n(2) -\n(3) *\n(4) /\n(5) sin(number1/number2)\n(6)  cos(number1/number2)\n(7)Swap numbers\n(8)quit")
     print("Selected numbers:",number1,number2)
     selection = int(input("Choose (1-8): "))
     if selection == 1:
         print("The answer is:", number1+number2)
     elif selection == 2:
         print("The answer is:", number1-number2)
     elif selection == 3:
         print("The answer is:", number1*number2)
     elif selection == 4:
         print("The answer is:", number1/number2)
     elif selection == 5:
         print("The answer is:", math.sin(number1/number2))
     elif selection == 6:
         print("The answer is:", math.cos(number1/number2))
     elif selection == 7:
         number1 = int(input("Give new first number: "))
         number2 = int(input("Give new second number: "))
     elif selection == 8:
         break
     else:
         print("Invalid selection.") 

我现在要做的是检查用户输入是否仅包含数字。 如果输入包含字符,程序将打印“无效输入”左右,然后它会再次询问数字(While 循环?)。 同样在选择中,我想检查选择编号是否在 1 到 8 之间,其他所有内容都会导致再次询问数字。

我听说过这个我可以用try: ... except (TypeError, ValueError) 做。但我无法让它工作。我需要考虑重写我的代码吗?

【问题讨论】:

  • 请格式化您的代码,使其清晰易读。

标签: python loops python-3.x error-handling calculator


【解决方案1】:

如果您只想检查输入是否只包含数字,它看起来像您想要标准库中的isdecimal,这会检查字符串是否包含有效的十进制数字。

示例用法:

>>> a = "123"
>>> a.isdecimal()
True
>>> b = "123foo"
>>> b.isdecimal()
False

另外,我强烈考虑使用字典来存储选项,这些选项存储由这些选项调用的函数,而不是您在此处拥有的大 if-else 块。我可以说更多,但这开始进入代码审查领域,这更适合https://codereview.stackexchange.com/

上的问题

【讨论】:

    猜你喜欢
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 2012-05-27
    • 2012-04-22
    • 1970-01-01
    • 2015-04-07
    • 1970-01-01
    相关资源
    最近更新 更多