2017-01-02 68 views
-1

我是相當新的python,並試圖開發一個計算器。我已經創建了它,以便在你按9並退出之前一直詢問你的問題。我做了一個錯誤,而這樣做的,它一直要求我輸入第一個號碼並不斷循環,這Python計算器代碼

loop = 1 
oper = 0 

while loop == 1:  
    num1 = input("Enter the first number: ") 
    print num1 

    oper = input("+, -, *, /,9: ") 
    print oper 

    num2 = input("Enter the second number: ") 
    print num2 

    if oper == "+": 
     result = int(num1) + int(num2) 
    elif oper == "-": 
     result = int(num1) - int(num2) 
    elif oper == "*": 
     result = int(num1) * int(num2) 
    elif oper == "/": 
     result = int(num1)/int(num2) 
    elif oper == "9": 
     loop = 0 


    print "The result of " + str(num1) + str(oper) + str(num2) + " is " + str(result) 

    input("\nPress 9 to exit.") 
+4

修復壓痕請 – depperm

回答

0

您有相關問題,壓痕和這裏是一個更好的辦法利用休息while循環退出:

loop = 1 
oper = 0 

while loop == 1: 

    x = input("Press 9 to exit otherwise anything to continue:")#much better way 
    if x == "9": 
     break 
    num1 = input("Enter the first number: ") 
    print (num1) 

    oper = input("+, -, *, /: ") 
    print (oper) 

    num2 = input("Enter the second number: ") 
    print (num2) 

    if oper == "+": 
     result = int(num1) + int(num2) 
    elif oper == "-": 
     result = int(num1) - int(num2) 
    elif oper == "*": 
     result = int(num1) * int(num2) 
    elif oper == "/": 
     result = int(num1)/int(num2): 
    else: 
     print("Invalid operator!") #if user inputs something else other than those 


    print ("The result of " + str(num1) + str(oper) + str(num2) + " is " + str(result)) 
1

這是因爲你做任何事情首先打破。試着改變你的oper包括9

oper = raw_input("+, -, /, *, or 9 (to exit)":) 

然後包括elif聲明並更改loop 0退出while循環:

elif oper == "9": 
    loop = 0 

而且,處理您的縮進:

loop = 1 

while loop == 1:  

    num1 = input("Enter the first number: ") 
    print num1 

    oper = input("+, -, *, /,9: ") 
    print oper 

    num2 = input("Enter the second number: ") 
    print num2 

    if oper == "+": 
     result = int(num1) + int(num2) 
    elif oper == "-": 
     result = int(num1) - int(num2) 
    elif oper == "*": 
     result = int(num1) * int(num2) 
    elif oper == "/": 
     result = int(num1)/int(num2) 
    elif oper == "9": 
     loop = 0 


print "The result of " + str(num1) + str(oper) + str(num2) + " is " + str(result) 
+0

應該是「循環= 0」,不應該嗎?循環= 1將導致它保持循環。 – EJoshuaS

+0

@EJoshuaS是的,這是 –

1

這個問題似乎是你沒有縮進。 Python關心你縮進多少,因此只有縮進行將被視爲while循環的一部分。這裏只有第一行(num1 = input...)被認爲是while循環的一部分。解決這個問題的最簡單方法是在應該在循環中的每一行之前添加四個空格(以及在if語句中的每行之前另外添加四個空格)。

有關更多幫助,請參閱http://www.diveintopython.net/getting_to_know_python/indenting_code.html

+0

這裏*的縮進不正確,但是OP沒有提到任何錯誤。這裏的OP的問題是如何退出循環 –

+0

但缺乏'break'不是問題,因爲他設置了'loop = 0',並且循環條件是'while循環== 1',所以它應該中斷。他說,只有循環的第一行纔會到達,這意味着它是唯一被視爲循環的一部分的行(可能他的Python解釋器以這種方式工作,而不是給出錯誤)。 –

+1

我下注行num1 =輸入(...和打印num1是縮進,但不是其他人,所以它只循環詢問第一個數字,甚至可能只有行num1 =輸入(...是 – Lex