計算機を書きましたが、2つまたは3つの数字を入力できます。 は現在、これは私が持っているものです。値が入力されたかどうかのテスト
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))
どのように私はそれを動作させるのですか? split()アクションに5つの変数が必要であるというエラーが表示されますが、これは意味があります。私の質問は私が何をすることができるのですか(どのような方法で)できますか?
全コード:
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
分割の結果に5つの変数を割り当てようとしています。戻り値に5つのものがない場合は、エラーが書き込まれています。変数の束ではなく、1つのリストに戻り値を取り込むことができます。 'parts = user_input.split()'です。次に、 'len(parts)== 5:...'などをチェックすることができます。 – khelwood