Interacting with raw_input

Python also has a feature which lets you interact with the outside world to get input.  The raw_input() function waits for the user to type some input and press return.  It then gets whatever was typed.

>>> raw_input()
some input
'some input'

It’s not obvious what is going on here.  When you hit return at the end of the first line, a blank line appears.  You type what you want into the line and when you hit enter Python gets the line and (in this case, because we’re in an interactive window) prints what it got.  Do it yourself to see, because the text doesn’t show how it happens.

We might have instead assigned the input to a placeholder:

>>> a = raw_input()
some more input, where is it all going?
>>> # note it hasn't printed anything?
>>> a
'some more input, where is it all going?'

In a program this allows us to get information into the program, which might come in handy for maths (aka ‘math’) homework:

>>> a=raw_input()
>>> b=raw_input()
>>> a+b

Ooops!  The input that Python is getting is returned to us as strings.  And strings have a funny form of plus called concatenation.  We can use what we learned earlier to push this input into numbers:

>>> int(a)+int(b)

That’s what we were looking for (notice that there are no quotes around 68, because it’s a number now).

We are working in the interactive shell at the moment so the context of what is going on is clear.  However, when running a python program “in the wild” there won’t be that context.  You can add some information for the user if you put a message inside the raw_input brackets.  The message must be a string – so it must have quotes or it must be a variable which holds something which has quotes:

>>> a=raw_input('Enter your number here: ')
Enter your number here: 34

Can you see the string has been reproduced in front of the place you type?  This is called a ‘prompt’ because it prompts you to enter something.

About these ads

2 Responses to Interacting with raw_input

  1. Pingback: Consolidation: CryptoPyThy « Python Tutorials for Kids 8+

  2. Casey says:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 69 other followers

%d bloggers like this: