我正在創建一個計算購買房屋價值的代碼。它會詢問用戶大量的輸入,並且我想確保程序在輸入非整數時詢問整數。我可以通過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.")
您確定包含'integer_check'的正確版本嗎?這個版本看起來應該總是返回「真」。 –
[處理異常](https://docs.python.org/3/tutorial/errors.html#handling-exceptions) – wwii