2016-09-17 50 views
1

剛剛在幾個小時前啓動了python,並發現了一個問題。 The blow snippet表明最初我將userInput存儲爲1或2,然後執行if塊。問題是代碼直接跳轉到其他地方(即使我在控制檯窗口中鍵入1)。 我知道我犯了一個簡單的錯誤,但任何幫助將不勝感激。我的代碼跳過了IF塊並轉到其他地方

使用Python 3.5 ===在Visual Studio 2015運行===具體的CPython

userInput = float(input("Choose 1 (calculator) or 2 (area check)\n")) 
if(userInput =='1') : 
    shape = input("Please enter name of shape you would like to calculate the area for\n") 

if(shape == 'triangle') : 
    base = int(input("Please enter length of BASE\n")) 
    height = int(input("Please enter HEIGHT\n")) 
    print("The area of the triangle is %f" % ((base * height)*0.5)) 

elif (shape == 'circle') : 
    radius = int(input("Please enter RADIUS\n")) 
    print("The Area of the circle is %f" % ((radius**2)*22/7)) 

elif (shape == 'square') : 
    length = int(input("Please Enter LENGTH\n")) 
    print("The area of the square is %f" % ((length**2)*4)) 

else : 
    initial1 = float(input("Please enter a number\n")) 
    sign1 = input("please enter either +,-,*,/ \nwhen you wish to exit please type exit\n") 
    initial2 = float(input("Please enter number 2\n")) 
if(sign1 == '+') : 
    answer = float(initial1) + float(initial2) 
    print(answer) 
elif(sign1 == '*') : 
    answer = float(initial1) * float(initial2) 
    print(answer) 
elif(sign1 == '-') : 
    answer = float(initial1) - float(initial2) 
    print(answer) 
elif(sign1 == '/') : 
    answer = float(initial1)/float(initial2) 
    print(answer) 

PS。如果[可能]你能保持儘可能基本的幫助,因爲我想確保我完全理解基礎知識。

感謝您的幫助! :D

+0

你正在轉換爲浮動,但比較字符串 –

回答

1

您正在將您的輸入轉換爲浮點數,但檢查數字的字符串。將其更改爲:

If userInput == 1.0: 

或者更好的是,保持它的方式,並且不要將用戶輸入轉換爲浮動。只需要將輸入轉換爲floatint如果您想對其進行數學運算。在你的情況下,你只是用它作爲選項,所以你可以保留它作爲一個字符串:

userInput = input("Choose 1 (calculator) or 2 (area check)\n") 

P.S.確保在Python中對縮進非常小心。我假設你的代碼編輯器中的縮進是正確的,但是在粘貼到這個站點時也要小心。你在這裏擁有同一層次的所有東西,但爲了使程序正常工作,需要進一步縮進一些if塊。

+0

非常感謝你@elethan - 完美的工作。虐待堅持刪除「浮動」,因爲它更有意義。 –

相關問題