所以我对编程很新,但我只是在研究一个简单的计算器.
当我启动程序并尝试除法部分(试图将5除以2)时,输出为3.0.这两个数字是浮点数,所以我真的不明白为什么这不起作用.其次,乘法也给出了错误的答案.
from math import *
while True:
print("Options:")
print("Enter 'add' to add two numbers")
print("Enter 'subtract' or '-' to subtract two numbers")
print("Enter 'multiply' to multiply two numbers")
print("Enter 'divide' to divide two numbers")
print("Enter 'quit' to end the program")
user_input = input(": ")
if user_input == "quit":
print ("Calculator stopped.")
break
elif user_input == "subtract" or "-":
num1 = float(input("num1: "))
num2 = float(input("num1: "))
print(num1 - num2)
elif user_input == "multiply" or "*":
num1 = float(input("num1: "))
num2 = float(input("num1: "))
print(">> ", num1 * num2," <<")
elif user_input == "divide" or "/":
num1 = float(input("num1: "))
num2 = float(input("num1: "))
sum = num1 / num2
print(str(float(num1)/num2))
else:
print("Unknown command")
顺便说一句,我使用的是Python 3.6.1.
解决方法:
这不符合你的想法:
elif user_input == "subtract" or "-":
它的工作原理就好像按如下方式分组:
elif (user_input == "subtract") or "-":
无论user_input的值如何,此条件将评估为True(因为“ – ”为非空且因此为True)并且将执行减法.
(tried to divide 5 by 2), the output was 3.0
那是因为5减2是3.代码减去.
你想要更像的东西:
from math import *
while True:
print("Options:")
print("Enter 'subtract' or '-' to subtract two numbers")
print("Enter 'multiply' to multiply two numbers")
print("Enter 'divide' to divide two numbers")
print("Enter 'quit' to end the program")
user_input = input(": ")
if user_input == "quit":
print ("Calculator stopped.")
break
elif user_input in ( "subtract", "-"):
num1 = float(input("num1: "))
num2 = float(input("num1: "))
print(num1 - num2)
elif user_input in ("multiply", "*"):
num1 = float(input("num1: "))
num2 = float(input("num1: "))
print(">> ", num1 * num2," <<")
elif user_input in ("divide", "/"):
num1 = float(input("num1: "))
num2 = float(input("num1: "))
print(num1/num2)
else:
print("Unknown command")