2017-06-01 95 views
0

創建將打印給用戶的條件語句的正確方法'錯誤:如果用戶沒有輸入,則此字段未填寫一個整數值。如何爲空int輸入創建條件語句(Python 3)

例如,對於這樣的說法:

user_Input = input('Enter a string: ') 
if not user_Input: 
    print('Error: This field has not been filled out') 
else: 
    print(user_Input) 

程序將打印(「錯誤:該字段尚未填寫」)是用戶沒有輸入值,但是如果我們做同樣的一個整數。假設:

user_Input = int(input('Enter an integer: ')) 
if not user_Input: 
    print('Error: This field has not been filled out') 
else: 
    print(user_Input) 

它會產生一個值錯誤。

ValueError: invalid literal for int() with base 10: '' 

我怎樣才能得到第二條語句與第一條語句具有相同的輸出,而沒有值錯誤。

回答

0

int("")無效,所以您需要驗證輸入字符串之前您試圖將其解析爲一個整數。

user_Input = input('Enter a string: ') 
if not user_Input: 
    print('Error: This field has not been filled out') 
else: 
    value = int(user_Input) 
    print(value) 

這隻能過濾空字符串;用戶仍然可以提供無效的字符串。而不是試圖阻止ValueError,只是抓住它。嘗試類似

while True: 
    user_input = input('Enter a int: ') 
    try: 
     value = int(user_input) 
    except ValueError: 
     print("Invalid integer '%s', try again" % (user_input,)) 
    else: 
     break