2017-06-14 99 views
0

美好的一天。我是創建python程序的新手。我的程序是編寫代碼,如果1存儲在垃圾郵件中打印出Hello,如果2存儲在垃圾郵件中打印Howdy,並打印問候語!如果其他東西存儲在垃圾郵件中。如何將空字符串轉換爲整數值0

我的問題是,我想重複該過程,如果用戶不會輸入任何內容或空值。我將如何將''轉換爲值0.謝謝。對不起,如果我的程序不太好。

while True: 
    print ('Enter value of spam') 
    spam = int(input()) 
    if spam == 1: 
     print ('Hello') 
     continue 
    elif spam == 2: 
     print ('Howdy') 
     continue 
    elif spam != 0: 
     print ('Greeting') 
     continue 

回答

0

試試這個。

print ('Enter value of spam') 
spam = input() 
while spam != "" or spam == 0: 
    if int(spam) == 1: 
    print ('Hello') 
    elif int(spam)== 2: 
    print ('Howdy') 
    elif int(spam)!= 0: 
    print ('Greeting') 
    print ('Enter value of spam') 
    spam = input() 
0

你可以使用try-except塊來處理您的用戶的輸入不能被理解爲一個整數任何情況下:

while True: 
    print ('Enter value of spam') 
    try: 
     spam = int(input()) 
    except ValueError: 
     spam = 0 
    if spam == 1: 
     print ('Hello') 
     continue 
    elif spam == 2: 
     print ('Howdy') 
     continue 
    elif spam != 0: 
     print ('Greeting') 
     continue 
+0

我想我是太愚蠢,我不知道在if語句中使用int轉換。而且try-except塊也有很大幫助。非常感謝你們。 – Lyle