我被要求用python编写一个计算器代码,这就是我的工作原理:
operation = input("please input your operation (+,-,*,/): ")
number_1 = int(input("Please enter your first number: "))
number_2 = int(input("Please enter your second number: "))
if operation == '+':
print("result: ",(number_1 + number_2))
elif operation == '-':
print("result: ",(number_1 - number_2))
elif operation == '*':
print("result: ",(number_1 * number_2))
elif operation == '/':
print("result: ",(number_1 / number_2))
else:
print("Invalid input")
现在,我只想添加一个限定符,如果用户输入0作为“ number_2”,程序将显示“错误!无法除以0 !!”
答案 0 :(得分:4)
一种选择是在执行计算之前仅检查number_2
是否包含零:
elif operation == '/':
if number_2 != 0:
print("result: ",(number_1 / number_2))
else:
print("Cannot divide by 0")
另一种选择是捕获每次尝试除以ZeroDivisionError
时抛出的0
:
elif operation == '/':
try:
print("result: ",(number_1 / number_2))
except ZeroDivisionError:
print("Cannot divide by 0")
答案 1 :(得分:3)
从更改代码:
operation = input("please input your operation (+,-,*,/): ")
number_1 = int(input("Please enter your first number: "))
number_2 = int(input("Please enter your second number: "))
if operation == '+':
print("result: ",(number_1 + number_2))
elif operation == '-':
print("result: ",(number_1 - number_2))
elif operation == '*':
print("result: ",(number_1 * number_2))
elif operation == '/':
print("result: ",(number_1 / number_2))
else:
print("Invalid input")
收件人:
operation = input("please input your operation (+,-,*,/): ")
number_1 = int(input("Please enter your first number: "))
number_2 = int(input("Please enter your second number: "))
if operation == '+':
print("result: ",(number_1 + number_2))
elif operation == '-':
print("result: ",(number_1 - number_2))
elif operation == '*':
print("result: ",(number_1 * number_2))
elif operation == '/':
if number_2 == 0 :
print ("Error! Cannot divide by 0!!!")
else:
print("result: ",(number_1 / number_2))
else:
print("Invalid input")
答案 2 :(得分:2)
在您的if
判断代码段中嵌套一个'/'
。
operation = input("please input your operation (+,-,*,/): ")
number_1 = int(input("Please enter your first number: "))
number_2 = int(input("Please enter your second number: "))
if operation == '+':
print("result: ",(number_1 + number_2))
elif operation == '-':
print("result: ",(number_1 - number_2))
elif operation == '*':
print("result: ",(number_1 * number_2))
elif operation == '/':
if number_2 == 0:
print("Error! Cannot divide by 0!!!")
else:
print("result: ",(number_1 / number_2))
else:
print("Invalid input")
答案 3 :(得分:0)
我们不能除以0。
但是请使用异常处理Python exception handling
解决此问题see here why can't divide by zero
const screen = {
component: {
name: "mad.app.Dummy",
}
}