【发布时间】:2020-06-24 17:01:16
【问题描述】:
我是堆栈溢出网站、python 和整个编程的新手。如果这个问题的标题或正文不恰当,请原谅我。
我正在尝试用python创建一个简单的计算器程序,它只执行四种操作,即加法、减法(差)、乘法和除法。
这是我的代码:
print("Welcome to the calculator \n")
num1 = int(input("Enter the first number \n"))
num2 = int(input("Enter the second number \n"))
operation = (input("""Enter the symbol of the operation to be performed. Your choices are:
+
- (Difference)
*
/
\n """))
add = num1+num2
sub1 = num1-num2
sub2 = num2 - num1
product = num1*num2
quotient = num1 / num2
if operation == "-" :
if num1 > num2:
print(sub1)
else:
print(sub2)
elif operation == "+" :
print(add)
elif operation == "*" :
print(product)
elif operation == "/" :
if num2 == 0:
print("Sorry, can't divide a number by zero")
else:
print(quotient)
else:
print("Please enter a valid operator from among the ones provided above")
一切运行良好,除了当我输入零作为 num2 时,无论我选择什么运算符,输出 这是:
Traceback (most recent call last):
File "test4.py.txt", line 19, in <module>
quotient = num1 / num2
ZeroDivisionError: division by zero
非常感谢您的帮助。谢谢!
【问题讨论】:
-
这是个例外
标签: python-3.x python-3.6