You are here

Keyboard input

1 September, 2015 - 16:57

The programs we have written so far are a bit rude in the sense that they accept no input from the user. They just do the same thing every time.

Python 2 provides a built-in function called raw_input that gets input from the keyboard. In Python 3, it is called input. 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.

>>> text = raw_input()What are you waiting for?>>> print textWhat are you waiting for?

Before getting input from the user, it is a good idea to print a prompt telling the user what to input. raw_input can take a prompt as an argument:

>>> name = raw_input('What...is your name?\n')What...is your name?Arthur, King of the Britons!>>> print nameArthur, King of the Britons!

The sequence \n at the end of the prompt represents 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:

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

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() with base 10

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