2016-09-28 32 views
-2

每當我測試我的計算器,看看它如何處理輸入不是數字,它會標記一個ValueError。更確切地說,這一個「ValueError:無法將字符串轉換爲浮點數:'a'」。我試圖修改這個,所以有一個解決方案來處理非整數,但無濟於事......非常感謝幫助。我的初學python項目(計算器)有輸入問題

這裏是我到目前爲止的代碼:

print("1. ADDITION ") 
print("2. MULTIPLICATION ") 
print("3. TAKEAWAY ") 
print("4. DIVISION ") 

Operator = int(input("please enter one of the numbers above to decide the operator you want. ")) 

while Operator > 4: 
    print("Please select a number from the options above. ") 
    Operator = int(input("please enter one of the numbers above to decide the operator you want. ")) 
    if Operator != (1 or 2 or 3 or 4): 
     print("please enter one of the options above. ") 
     Operator = int(input("please enter one of the numbers above to decide the operator you want. ")) 
    continue 

while True: 
    Num1 = float(input("Please enter first number. ")) 
    if Num1 == float(Num1): 
     print("thanks! ") 
    elif Num1 != float(Num1): 
     Num1 = float(input("Please enter first number. ")) 
    break 

while True: 
    Num2 = float(input("Please enter second number. ")) 
    if Num2 == float(Num2): 
     print("thanks ") 
    elif Num1 != float(Num1): 
     Num1 = float(input("Please enter first number. ")) 
    break 
+0

您需要查看['try/except'](https://docs.python.org/3/tutorial/errors.html#handling-exceptions)塊。 –

+0

...並在這裏的解決方案將告訴你如何:http://stackoverflow.com/questions/8420143/valueerror-could-not-convert-string-to-float-id –

回答

1

異常處理是什麼你在找什麼。 Smthng這樣的:

input = 'a' 
try: 
    int(a) 
except ValueError: 
    print 'Input is not integer' 
0

注意:應在小寫根據PEP8命名變量,請參閱:What is the naming convention in Python for variable and function names?

如果要重新輸入,直到你沒有得到ValueError,把它放在一個循環:

print("Please select a number from the options above.") 
while True: 
    try: 
     operator = int(input("please enter one of the numbers above to decide the operator you want: ")) 
    except ValueError: 
     print("Sorry, not a number. Please retry.") 
    else: 
     if 1 <= operator <= 4: 
      break 
     else: 
      print("Sorry, choose a value between 1 and 4.") 

注:使用input與Python 3.x或raw_input與Python 2.7

1. ADDITION 
2. MULTIPLICATION 
3. TAKEAWAY 
4. DIVISION 
Please select a number from the options above. 
please enter one of the numbers above to decide the operator you want: spam 
Sorry, not a number. Please retry. 
please enter one of the numbers above to decide the operator you want: 12 
Sorry, choose a value between 1 and 4. 
please enter one of the numbers above to decide the operator you want: 2 
+0

感謝Laurent,非常感謝的人。 –

+0

歡迎您。你解決了你的問題嗎? Python很棒,不是嗎? –