【发布时间】:2016-12-22 16:06:59
【问题描述】:
我写了一个计算器,我希望能够输入两个数字或三个数字。 目前这就是我所拥有的:
def main():
action2=0
user_input=input("Enter a num1 act1 num2 act2 num3 (with a space between them): ") #Gets the values
var1, action1, var2, action2, var3=user_input.split() #assigns the values into the variables
if(action2==0):
calc2(float(var1), action1, float(var2))
else:
calc3(float(var1), action1, float(var2), action2, float(var3))
如何让它发挥作用? 它给了我一个错误,我需要 5 个变量来执行 split() 操作,这是有道理的。我的问题是我能做什么(以什么方式)我可以做我想做的事吗?
完整代码:
def calculate(num1, num2, act):
if(act=='+'):
total=num1+num2
elif(act=='-'):
total=num1-num2
elif(act=='*'):
total=num1*num2
elif(act=='/'):
total=num1/num2
else:
print("input not recognized")
return total
def calc2(var1, action1, var2):
if(action1=='/' and var2==0): #checks for division by 0
print("YOU CAN'T DIVIDE BY ZERO!!!")
else:
print(calculate(float(var1), float(var2), action)) #calls the 'calculating' function, recives and prints the total of act
def main():
action2=0 #testing if anything was entered as action2
user_input=input("Enter a num1 act1 num2 act2 num3 (with a space between them): ") #Gets the values
var1, action1, var2, action2, var3=user_input.split() #assigns the values into the variables
if(action2==0): #two num calc
calc2(float(var1), action1, float(var2))
else: #three num calc
calc3(float(var1), action1, float(var2), action2, float(var3))
def calc3(var1, action1, var2, action2, var3):
if(action1=='/' and var2==0 or action2=='/' and var3==0): #checks for division by 0
print("YOU CAN'T DIVIDE BY ZERO!!!")
elif((action2=='*' or action2=='/') and (action1=='+' or action2=='-')): #checks if act2 should be done before act1 (order of operation) total=calculate(float(var2), float(var3), action2) #calls the 'calculating' function, recives the total of act2
total=calculate(float(var2), float(var3), action2)
print(calculate(float(var1), float(total), action1)) #calls the 'calculating' function, assigns the total of act2 as num2, recives and prints the total of act1
else: #act1 is done before act2 (order of operation)
total=calculate(float(var1), float(var2), action1) #calls the 'calculating' function, recives the total of act1
print(calculate(float(total), float(var3), action2)) #calls the 'calculating' function, assigns the total of act1 as num1, recives and prints the total of act2
main() #starts program
【问题讨论】:
-
您正在尝试将五个变量分配给拆分结果。如果返回值中没有五样东西,你就写了一个错误。您可以在一个列表而不是一堆变量中捕获返回值。
parts = user_input.split()。然后你可以检查if len(parts)==5: ...等。
标签: python python-3.x input user-input calculator