user5482109
user5482109

Reputation: 23

Python: looping raw input

I'm new to python and I am having trouble getting python to loop through a raw_input if there is no input and to loop through the question again until there is an input. Once there is an input move to the next question e.g.

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: ")

I know this code is all jacked up. Just trying to learn.

Upvotes: 2

Views: 961

Answers (3)

Yann
Yann

Reputation: 51

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: ")  

This loop will never stop, because the again is always None

Upvotes: 0

You have a bug in your code. You check "again == None" in the loop, but never change "again" value, so it always equals to "None" and loop never stops.

You can wrap input logic into a function and then ask multiple questions:

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))

Upvotes: 0

davejagoda
davejagoda

Reputation: 2528

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

Upvotes: 1

Related Questions