所以我正在制作我的简单计算器,这是我到目前为止所做的:
import time
print ("Welcome. This is a calculator that uses the function: A (operator) B.")
time.sleep(3.5)
print ("Available operators include: Addition, Subtraction, Multiplication, Division, Exponent, and Remainder division.")
time.sleep(3.5)
while True:
a = float(input("Type in a value of A. "))
b = float(input("Type in a value of B. "))
opera = input("Would you like to: Add - Subtract - Multiply - Divide - Exponent - or Remainder? ")
opera = opera.lower()
while not (opera) == "add" or (opera) == "subtract" or (opera) == "multiply" or (opera) == "divide" or (opera) == "exponent" or (opera) == "remainder":
print ("Invalid operation.")
opera = input("Would you like to: Add - Subtract - Multiply - Divide - Exponent - or Remainder? ")
break
if (opera) == "add":
print ((a) + (b))
if (opera) == "subtract":
print ((a) - (b))
if (opera) == "multiply":
print ((a) * (b))
if (opera) == "divide":
print ((a) / (b))
if (opera) == "exponent":
print ((a) ** (b))
if (opera) == "remainder":
print ((a) % (b))
cont = input("Would you like to do another problem?")
cont = cont.lower()
if cont != "yes":
break
quit
因此,当我启动计算器并为a和b输入值时,除了add之外的任何内容都会导致无效操作。然后它会提示我进行有效的操作,然后它适用于所有操作。我该如何解决这个问题?我假设问题与while有关,而不是在while内。
答案 0 :(得分:1)
我认为这是一个括号问题。
while not (opera) == "add" or (opera) == "subtract" or (opera) == "multiply" or (opera) == "divide" or (opera) == "exponent" or (opera) == "remainder":
应该是
while not ((opera) == "add" or (opera) == "subtract" or (opera) == "multiply" or (opera) == "divide" or (opera) == "exponent" or (opera) == "remainder"):
你的不只是申请第一个学期,“添加”。 它之后起作用的原因是你永远不会因为休息而回到没有条件的时候。
我认为字典是解决此类问题的一种更优雅的方式。
答案 1 :(得分:0)
您的脚本实际上存在许多问题。请参阅我在下面进行的修改:
operations =('add','subtract','multiply','divide','exponent','remaining')
print(“欢迎。这是一个使用该功能的计算器:A(操作员)B。\ n”) print(“可用运算符包括:{0}”。格式(操作))
虽然是真的: a = float(raw_input(“输入值A”)) b = float(raw_input(“输入值B”))
opera = raw_input("Which operation would you like to perform? ")
opera = opera.lower()
while opera not in operations:
print ("Invalid operation.")
opera = raw_input("Which operation would you like to perform? ")
if opera == "add":
print (a + b)
if opera == "subtract":
print (a - b)
if (opera) == "multiply":
print (a * b)
if (opera) == "divide":
print (a / b)
if (opera) == "exponent":
print (a ** b)
if (opera) == "remainder":
print (a % b)
if raw_input("Would you like to do another problem?").lower() != 'yes':
break
问题0:从用户的角度来看,睡眠语句总是很有用,并且它在测试调试运行中增加了7秒。摆脱它们。如果你真的......真的......想要它们,那么在你完成后再添加它们。
问题1:您使用了输入函数而不是raw_input函数。 Read the python docs,输入函数对您输入的内容执行eval语句。当我尝试执行'add'命令时,我收到了一个NameError。请改用raw_input。
问题2:你的逻辑在while语句中是错误的。你可以说while(opera!='add)或...但我选择将所有有效值添加到元组中。它更干净,更整洁。打破循环的逻辑也是错误的。无论输入是什么,你都会打破循环,你也可以使用if语句来达到同样的效果。
问题3:这会尖叫c style switch语句,所以请使用字典。我会使用字典将操作的字符串形式(例如'add','multiply')与函数ponters联系起来。这将是一个非常清晰,更加pythonic。如果你愿意,我可以发布使用字典的代码。