Python:循环原始输入

时间:2015-11-02 01:24:41

标签: python while-loop

我是python的新手,如果没有输入,我无法让python循环遍历raw_input,并且在有输入之前再次循环问题。一旦有输入移动到下一个问题,例如

again = None
while again == None:
    name = raw_input("Hello, please enter your name?: ")
    if name:
        print "Hello %s I am soandso" % name
again = raw_input("Please type a name: ")

我知道这段代码全都搞砸了。只是想学习。

3 个答案:

答案 0 :(得分:1)

name = None
while not name:
    name = raw_input("Hello, please enter your name?: ")
    if name:
        print "Hello %s I am soandso" % name

答案 1 :(得分:0)

您的代码中存在错误。你再次检查" = =无"在循环中,但永远不会改变"再次"价值,所以它总是等于"无"并且循环从不停止。

您可以将输入逻辑包装到函数中,然后提出多个问题:

def get_value(question):
    while True:
        response = raw_input(question)
        if response:
            return response


answer1 = get_value('What is your first name? ')
answer2 = get_value('What is your last name? ')

print('First name: {}, last name: {}'.format(answer1, answer2))

答案 2 :(得分:0)

again = None
while again == None:
    name = raw_input("Hello, please enter your name?: ")
    if name:
        print "Hello %s I am soandso" % name
again = raw_input("Please type a name: ")  

此循环永远不会停止,因为再次始终为None