2017-06-14 188 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