所以我对编程非常陌生,但我正在研究一个简单的计算器。 当我启动程序并尝试除法部分(试图将5除以2)时,输出为3.0。这2个数字是浮点数,所以我不太明白为什么这不起作用。其次,乘法也给出了错误的答案。
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")
BTW我使用的是Python 3.6.1。
答案 0 :(得分:6)
这不符合你的想法:
elif user_input == "subtract" or "-":
它的工作方式如下:
elif (user_input == "subtract") or "-":
无论user_input
的值如何,此条件将评估为True(因为"-"
非空且因此为True)并且将执行减法。
(试图将5除以2),输出为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")