while循环中不必要的输出

时间:2017-02-14 22:37:42

标签: python loops while-loop

我有一个循环,所以如果用户输入一个字符串,它会要求他们输入一个整数,并且除了从早期代码输出一行之外它工作正常。不知道如何摆脱它。

while True : #loops input 
    userAge = raw_input("please enter your age: ")
    if  (userAge > 18) : #outputs based on age input 
        print "Congrats, you're an adult."
        continue 
    elif userAge <= 0 :
        print "You got a computer in that womb?"
        continue
    elif userAge <= 5 :   
        print "You're a toddler, get off the computer!"
        continue
    elif userAge <= 10:
        print "You're a child!"
        continue
    elif userAge <= 12:
        print "You're a preteen, go listen to fall out boy."
        continue
    elif userAge > 12:
        print "You're a teen!"
        continue
    try :
        userAge = int(userAge) 
    except ValueError :
        print ("Please enter an integer you dummy!")
        continue
    else : 
        break

当有人输入字符串时的输出如下所示:

恭喜你是一个成年人 把你假的整数! 请输入您的年龄:

我想摆脱恭喜你是一个成年人

3 个答案:

答案 0 :(得分:0)

你应该把

try...except...else

中实际检查userAge之前将userAge srting转换为整数的

语句

if...elif

语句

答案 1 :(得分:0)

在python中有两个函数可以获取用户输入,称为from pyfcm import FCMNotification apikey ="apikey" push_service = FCMNotification(api_key=apikey) registration_id = "regid" message_title = "Uber update" message_body = "Hope you're having fun this weekend, don't forget to check today's news" result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body) print (result) inputraw_input未评估数据并返回raw_inputstring会评估您输入的内容,并会返回评估结果。

字符'0'(48),'1'(49),'2'(50),...的十进制值都大于18,因此代码中的第一个input计算结果为true

所以试试:

if

答案 2 :(得分:0)

if

尝试这样的事情!

问题是if..elif语句根据它们的ASCII值计算字符串,所以每个char对于duplicated语句之一都是真的