python - Python 3-计算器错误处理

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

我正在使用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.") 

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

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

最佳答案

如果只想检查输入内容中是否包含标准库中的 isdecimal ,那么它会检查字符串是否包含有效的十进制数字。

用法示例:

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

我也强烈考虑使用字典来存储选择,该选择存储的是被这些选择调用的函数,而不是您在此处拥有的大if-else块。我可以说更多,但这已经开始进入代码审查 Realm ,这在解决https://codereview.stackexchange.com/时更合适

关于python - Python 3-计算器错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32061871/

相关文章:

python - 按用法对单词排序

loops - 了解循环不变式。寻找并证明它们的算法

javascript - JS : Iterate over page & convert US Dollars to Rands

python - 读取非常大的一行文本文件

python - 可以使用 while(file >> ...) C++ 习惯用法来读取 Cython 中的文件吗?

启动脚本时,Python 日志消息出现在 stdout 中

python - 如何使用 Sikuli 中的 “type” 函数检查变量类型

java - 创建一个二维字符串数组 anArray[2][2]

python - Qt 和 opencv 应用程序无法在虚拟环境中运行

python - numpy.memmap 无法处理非常大的数据