You are here

Asking the user for input

23 February, 2015 - 11:59

Sometimes we would like to take the value for a variable from the user via their keyboard. Python provides a built-in function called raw_input that gets input from the keyboard 1. When this function is called, the program stops and waits for the user to type something. When the user presses Return or Enter, the program resumes and raw_input returns what the user typed as a string.

>>> input = raw_input()Some silly stuff>>> print inputSome silly stuff

Before getting input from the user, it is a good idea to print a prompt telling the user what to input. You can pass a string to raw_input to be displayed to the user before pausing for input:

>>> name = raw_input('What is your name?\n')What is your name?Chuck>>> print nameChuck

The sequence \n at the end of the prompt represent s a newline, which is a special character that causes a line break. That’s why the user’s input appears below the prompt.

If you expect the user to type an integer, you can try to convert the return value to int using the int() function:

>>> prompt = 'What...is the airspeed velocity of an unladen swallow?\n'>>> speed = raw_input(prompt)What...is the airspeed velocity of an unladen swallow?17>>> int(speed)17>>> int(speed) + 522

But if the user types something other than a string of digits, you get an error:

>>> speed = raw_input(prompt)What...is the airspeed velocity of an unladen swallow?What do you mean, an African or a European swallow?>>> int(speed)ValueError: invalid literal for int()

We will see how to handle this kind of error later.