【发布时间】: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