Interacting with raw_input
July 1, 2010 2 Comments
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() 45 >>> b=raw_input() 23 >>> a+b '4523'
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) 68
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.