2017-09-24 50 views
0

我正在創建一個計算購買房屋價值的代碼。它會詢問用戶大量的輸入,並且我想確保程序在輸入非整數時詢問整數。我可以通過Python來評估ValueError輸入嗎?

我做了一個函數來檢查一個輸入是否是一個整數,但是如果我輸入一個字符串,解釋器只會返回一個值錯誤。輸入後是否可以通過整數檢查函數運行字符串?

var=True 

print('Welcome to the interest calculator program.') 

def integer_check(input): 
    try: 
     return True 
    except ValueError: 
     return False 

while var==True: 
    num=int(input('Enter the price of your dream house: \n')) 
    if integer_check(num)==True: 
     if num>=0: 
      print('yay') 
     elif num<=0: 
      print('House price must be a positive number only. Please try again.') 
    elif integer_check(num)==False: 
     print("Sorry, that's not a number. Please try again.") 
+0

您確定包含'integer_check'的正確版本嗎?這個版本看起來應該總是返回「真」。 –

+0

[處理異常](https://docs.python.org/3/tutorial/errors.html#handling-exceptions) – wwii

回答

1

環繞try .. except ..約在int(..)呼叫;一旦發生異常,檢查int()調用的返回值是沒有意義的,因爲如果輸入字符串不是整數字符串,控制流將不會到達那裏。

try: 
    num = int(input('Enter the price of your dream house: \n')) 
except ValueError: 
    # Non-integer 
else: 
    # Integer 

傳遞字符串的函數,該函數應該嘗試轉換爲int:

print('Welcome to the interest calculator program.') 

def integer_check(s): 
    try: 
     int(s) 
     return True 
    except ValueError: 
     return False 
    return True 

while True: 
    num = input('Enter the price of your dream house: \n') 
    if integer_check(num): 
     num = int(num) 
     if num >= 0: 
      print('yay') 
      break 
     else: # Use else 
      print('House price must be a positive number only. Please try again.') 
    else: # No need to call integer_check(..) again 
     print("Sorry, that's not a number. Please try again.") 
0

您可以強制類型轉換:

def integer_check(i): 
    try: 
     int(i) # will successfully execute if of type integer 
     return True 
    except ValueError: # otherwise return False 
     return False 

而且,因爲你只有一個合格/不合格條件,更改:

if integer_check(num)==True: 
    ... 
elif integer_check(num)==False: 
    ... 

發送至:

if integer_check(num): 
    ... 
else: 
    ... 
相關問題