2014-05-08 196 views
1

我在這裏研究了這個問題我發現了類似的問題,但這是不同的。我需要在我正在處理的代碼片段中驗證用戶輸入,如果用戶輸入不是0(這樣我工作正常)就需要輸出錯誤,如果輸入是非數字,則輸出錯誤,這裏是我的問題是。如果我使用輸入,而不是的raw_input我得到一個錯誤:輸入和用戶輸入驗證

NameError name 'Whatever I type in' is not defined 

我試過到目前爲止:

鑄造變量爲一個整數,並使用isNaN函數試圖但慘遭失敗,最後繞去使用ifs和elses的問題。這是迄今爲止工作的代碼。

def pints_to_litres(): 
    pints = 0 
    pints = input("Please enter the amount of Imperial Pints you would like converted into Litres >>>") 
    litres = pints * float(0.568261) 
    litres = "%.2f" % litres 
    print (""+str(pints)+ " Pint(s) is equal to " +str(litres)+ " Litre(s)") 
    if (pints < 0): 
     print("Invalid Input! Try Again") 
     pints_to_litres() 

謝謝你們提前 彼得Romaniuk

+0

不知道爲什麼編輯,這是Python代碼。 – user3578634

+1

你爲什麼不用'raw_input'? – honi

+0

我仍然遇到raw_input出錯「TypeError:無法乘以類型'float'的非int的序列」 – user3578634

回答

3

在這裏繼續我提高你的代碼:

def pints_to_litres(): 
    over = False 
    while not over: 
     try: 
      pints = int(raw_input("Please enter the amount of Imperial Pints you would like converted into Litres >>>")) 
      litres = pints * float(0.568261) 
      print (""+str(pints)+ " Pint(s) is equal to " +str(litres)+ " Litre(s)") 
      if (pints < 0): 
       print("Invalid Input! Try Again") 
      else: 
       over = True 
     except ValueError: 
      print("Invalid Input! Try Again") 
  • 的沒用設置用raw_input覆蓋之前;
  • 更改使用input有利於爲此設計的raw_input;
  • 如果該字符串無效,則會在int()再次轉換品質和循環時拋出ValueError;
  • 如果值太低,則會再次循環;
  • 正如你所看到的,我也改變了對函數的遞歸調用,就好像用戶總是失敗一樣,你最終會粉碎函數堆棧限制,並且失敗。
+1

謝謝你!這是完美的,完美的作品,最好的我現在可以看到我錯了那麼多謝謝:) – user3578634

+0

哈哈。作爲答案一次,「誰會輸入999999次數字?」「誰知道?也許你會的。「順便說一句,錯誤被稱爲RuntimeError。 – thecoder16

+0

這不是因爲它不可能發生,它**不能**發生!你永遠不知道將來如何使用代碼,你應該始終儘可能地使用代碼! – zmo

1
pints = raw_input("Please enter the amount of Imperial Pints you would like converted into Litres >>>") 
try: 
    pints = float(pints) 
except ValueError: 
    print("Invalid Input! Try Again") 
    pints_to_litres() 

然後用代碼

+0

這是不好的編程來遞歸一個函數,沒有做適當的遞歸。 – zmo

+1

同意。你的答案好多了。我儘可能少地改變op的代碼 – honi

+1

感謝您的幫助honi我設法用@zmo的修復來修復它。謝謝你試圖幫助我,我非常感謝:) – user3578634

1

試試這個:

try: 
    pints = float(raw_input("Please enter the amount of Imperial Pints you would like converted into Litres >>>\n")) 
    # Calculation ... 
except ValueError: 
    print "Error" 
+0

謝謝josip_grg它現在已被修復。感謝您的幫助。作爲初學者,任何幫助都是有幫助的,並教會我一些東西。 – user3578634

0

您可以檢查是否輸入的是數字BU使用.isdigit()試試這個

entry =raw_input("Please enter the amount of Imperial Pints you would like converted into Litres >>>") 
     if (not(entry.isdigit())): 
       print "not a number" 
       pints_to_litres() 
     else: 
       pints=(int)(entry)