2013-03-23 75 views
-1

雖然我輸入了一個數值,但它仍然給我一個錯誤。我不知道這是爲什麼發生..幫助某人?def python錯誤重複

def is_string(s): 
    rate = input(s) 
    try: 
     str.isalpha(rate) 
     print('There was an error. Please try again. Make sure you use numerical values and alpabetical. ') 
     return is_string(s) #ask for input again 
    except: 
     return rate 
ExRate = is_string('Please enter the exchange rate in the order of, 1 '+Currency1+' = '+Currency2) 

def is_string2(msg): 
    amount = input(msg) 
    try: 
     str.isalpha(amount) 
     print('There was an error. Please try again. Make sure you use numerical values. ') 
     return is_string2(msg) #ask for input again 
    except: 
     return amount 
Amount = is_string2('Please enter the amount you would like to convert:') 
+2

你在這裏做什麼? – Eric 2013-03-23 22:53:18

+1

閱讀['isalpha()'](http://docs.python.org/2/library/stdtypes.html#str.isalpha)的文檔,您可能會發現錯誤。 – millimoose 2013-03-23 22:54:05

+1

你的'try'子句的哪一部分是你期望拋出一個錯誤?打印「出現錯誤」不足以從「try」語句中斷開。 – Eric 2013-03-23 22:54:28

回答

4

您正在尋找這樣的事情?

def get_int(prompt, error_msg): 
    while True: 
     try: 
      return int(input(prompt)) 
     except ValueError: 
      print(error_msg) 


rate = get_int(
    'Please enter the exchange rate in the order of, 1 {} = {}' 
     .format(Currency1, Currency2), 
    error_msg="Rate must be an integer") 
amount = get_int(
    'Please enter the amount you would like to convert:', 
    error_msg="Amount must be an integer") 
+0

謝謝一堆!這實際上工作! :D – ConfusedChild24 2013-03-23 23:03:27

2

,我不知道你爲什麼使用異常時,你應該只使用if語句:

def is_string(s): 
    rate = input(s) 
    if str.isalpha(rate): 
     print('There was an error. Please try again. Make sure you use numerical values and alpabetical. ') 
     return is_string(s) #ask for input again 
    else: 
     return rate 
ExRate = is_string('Please enter the exchange rate in the order of, 1 '+Currency1+' = '+Currency2) 

def is_string2(msg): 
    amount = input(msg) 
    if str.isalpha(amount): 
     print('There was an error. Please try again. Make sure you use numerical values. ') 
     return is_string2(msg) #ask for input again 
    else: 
     return amount 
Amount = is_string2('Please enter the amount you would like to convert:') 
+0

我試過如果語句,但它並沒有爲我的代碼作爲一個整體,因爲我試圖創建貨幣轉換器。謝謝。 – ConfusedChild24 2013-03-23 22:57:45

1

你不應該使用try語句,我不認爲你應該使用isalpha()。 isnumeric()測試數字有效性。 isalpha()將爲「%# - @」之類的字符串返回false。

while True: 
    s = input("Enter amount: ") 
    if s.isnumeric(): 
     break 
    print("There was a problem. Enter a number.") 
+0

** - 1 *單音圓括號 – Eric 2013-03-23 23:26:29

+0

固定。現在代碼更加pythonic。 – DXsmiley 2013-03-24 00:14:31