【发布时间】:2020-06-29 21:31:20
【问题描述】:
我是 python 的新手,正在尝试制作计算器,但不知道如何制作 我正在制作一个计算器,它将接受用户的输入,直到用户输入 0,然后执行操作 但我被困在这里 如果有人可以帮助我完成这项工作,我将非常感谢他/她。
num = None
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
options = int(input("Enter Your Choice: "))
# For Addition or Option 1
if options == 1:
total = 0
while(num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total + num
print("Your Calculated Number is: {} ".format(total))
# For Subtraction or Option 2
elif options == 2:
total = 0
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num
print("Your Calculated Value is: {}".format(total))
# Multiplication for Option 3
elif options == 3:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total))
# Division for Option 4
elif options == 4:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total / num
print("Your Calculated Value is: {}".format(total))
# When User Wants to Exit
else:
print("Thank You for Using the Calculator")
【问题讨论】:
-
减法不起作用,因为您从未在该代码块中为
total分配初始值。如果还有其他问题,您需要告诉我们它是什么 - 如果生成了错误,我们期望完整的回溯消息;如果只是出乎意料的结果,我们需要看看您收到了什么,以及您的预期。 -
我通过添加总计 = 0 更改了减法代码,但是当用户输入第一个数字时出现问题,我的代码从总计中减去零,因此我的代码给了我首先是负值,然后减去其他负值将添加两个数字
-
当我必须从 5 中减去 3 时,答案应该是 2 但我的代码给了我 -8 因为 0-5 = -5 然后 -5-3 = -8 这就是我不想要的问题一开始它从 0 减到负
标签: python python-3.x python-2.7 calculator