raw_input function in Python
Now it is time to pick up the pace. I have got you doing a lot of printing so that you get used to typing simple things, but those simple things are fairly boring. What we want to do now is get data into your programs. This is a little tricky because you have to learn to do two things that may not make sense right away, but trust me and do it anyway. It will make sense in a few exercises.
Most of what software does is the following:
- Take some kind of input from a person.
- Change it.
- Print out something to show how it changed.
So far you have only been printing, but you haven’t been able to get any input from a person or change it. You may not even know what “input” means, so rather than talk about it, let’s have you do some and see if you get it. In the next exercise, we’ll do more to explain it.
1 print "How old are you?", 2 age = raw_input() 3 print "How tall are you?", 4 height = raw_input() 5 print "How much do you weigh?", 6 weight = raw_input() 7 8 print "So, you're %r old, %r tall and %r heavy." % ( 9 age, height, weight)
How old are you? 38 How tall are you? 6'2" How much do you weigh? 180lbs So, you're '38' old, '6\'2"' tall and '180lbs' heavy
- Go online and fi nd out what Python’s raw_input does.
- Can you fi nd other ways to use it? Try some of the samples you fi nd.
- Write another “form” like this to ask some other questions.
- Related to escape sequences, try to fi nd out why the last line has ‘6\’2″‘ with that \’ sequence. See how the single- quote needs to be escaped because otherwise it would end the string?
How do I get a number from someone so I can do math?
That’s a little advanced, but try x = int(raw_input()), which gets the number as a string from raw_input() then converts it to an integer using int().
I put my height into raw input like raw_input(“6’2”) but it doesn’t work.
You don’t put your height in there; you type it directly into your Terminal. First thing is, go back and make the code exactly like mine. Next, run the script, and when it pauses, type your height in at your keyboard. That’s all there is to it.
Why do you have a new line on line 8 instead of putting it on one line?
That’s so that the line is less than 80 characters long, which is a style that Python programmers like. You could put it on one line if you like.
What’s the difference between input() and raw_input()?
The input() function will try to convert things you enter as if they were Python code, but it has security problems so you should avoid it. When my strings print out there’s a u in front of them, as in u’35’. That’s how Python tells you that the string is Unicode. Use a %s format instead and you’ll see it printed like normal.