2014-11-06 26 views
0
loop = 1 

choice = 0 #holds the user choice for menu 

while (loop == 1): 
    print ("Welcome to calci.py") 
    print ("your options are:") 
    print (" ") 
    print ("1. Addition") 
    print ("2. Subtraction") 
    print ("3. Multiplication") 
    print ("4. Division") 
    print ("5. Quit calculator.py") 
    print (" ") 

    choice = input("Choose your option: ") 
    if (choice == 1): 
     add1 = input("Add this: ") 
     add2 = input("to this: ") 
     print (add1, "+", add2, "=", add1 + add2) 
    elif (choice == 2): 
     sub2 = input("Subtract this: ") 
     sub1 = input("from this: ") 
     print (sub1, "-", sub2, "=", sub1 - sub2) 
    elif (choice == 3): 
     mul1 = input("Multiply this: ") 
     mul2 = input("with this: ") 
     print (mul1, "*", mul2, "=", mul1 * mul2) 
    elif (choice == 4): 
     div1 = input("Divide this: ") 
     div2 = input("by this: ") 
     print (div1, "/", div2, "=", div1/div2) 
    elif (choice == 5): 
     loop = 0 

print ("Thankyou for using calci.py!") 

我是新來的蟒蛇世界,我已經編寫和編譯了計算器代碼,但它不工作,需要幫​​助!基本計算器程序不工作在Python空閒

+1

「不工作」不是一個特定的問題。任何錯誤?是邏輯錯誤?你爲什麼這麼想?你傳遞了什麼值?你回來了什麼?你期望什麼?你到目前爲止如何解決這個問題? – Ben 2014-11-06 06:53:59

+0

它爲我工作。請說明確切的錯誤/問題。 – 2014-11-06 06:54:36

+0

這是Python 3還是2?如果這是Python 2,我看到你正在使用整數除法... – irrelephant 2014-11-06 06:54:38

回答

1

您的代碼:

choice = input("Choose your option: ") 
if (choice == 1): 

這裏輸入將返回字符串輸出。所以在你的情況下,你需要這樣做:

choice = input("Choose your option: ") 
if (choice == '1'): 

然後它會工作。但請記住它將在上面的示例中連接兩個字符串。因此,可能需要將該字符串轉換爲整數,然後執行算術運算。

所以像

intchoice = int(choice) 
if (intchoice == 1): 

同樣需要遵循您的ADD1/ADD2和其他輸入參數,你可以使用。

0

我試圖在終端中運行你的代碼,並且它按給定的無限循環。 您最初將選項設置爲零,但您的代碼不處理零,因此它不知道該怎麼做纔會循環。 嘗試添加else塊和elif語句的結尾以捕獲elif未考慮的任何內容。 EX:

else: 
    print("Error") 
    loop=0 

我看到使用while循環,直到用戶退出不斷嘗試,使程序運行你的。 嘗試使用input()或raw_input()來獲取操作的用戶選擇。其他那麼偉大的工作!