Search code examples
pythoninputraw-input

Using multiple inputs for raw_input python


Hi this is my first question. I started working on learning python this week and I started making simple programs. I started making a raw_input program, so the console asks a question like "Hi how are you?" and no matter what you respond with it would say the same thing. Is there a way I could make it so that if I say good it would say "Awesome!..." then ask another question like "Awesome! How old are you?" Something like that? This is my simple code so far.

print "Hello! THis is a simple program created by myselF! It will ask a variety of simple questions!"

how_are_you = raw_input("How are you?")
print how_are_you

age = raw_input("Good, glad to hear it! How old are you?") # Or "Aw thats not good hopefully this will change that. blah blah blah.
print age

Solution

  • Yes, go ahead and take a look at if statements, and flow of control. In short, if lets you do some things if a condition is true. In this example, it could be something like:

    how_are_you = raw_input("How are you? ")
    if how_are_you == 'good':
        print 'Awesome!'
    

    You can also use else or elif to have multiple branches:

    how_are_you = raw_input("How are you? ")
    if how_are_you == 'good':
        print 'Awesome!'
    elif how_are_you == 'great':
        print 'Fantastic!'
    else: # if how_are_you is anything except 'good' or 'great'.
        print "that's not so good..."
    

    And there's much, much more with making sure sensical things work (if the user types "Good" this chunk won't catch it- you'd need to use the .lower() functionality to compare regardless of case, or in to verify that punctuation won't kill it.). if...elif...else chains can be arbitrarily long, so you can have as many options and unique responses.

    You can also chain conditions with and and or if you want to use the same response for multiple inputs.