[Tutor] Other ways to use raw_input function

Alan Gauld alan.gauld at btinternet.com
Wed Oct 19 01:14:13 CEST 2011


On 18/10/11 18:58, amt wrote:

> After reading from docs.python.org <http://docs.python.org> I found out
> that this function can perform standard output without a trailing
> newline.

It can print a prompt message, yes.

 > Also it can take an input line, convert it as a string

It doesn't convert it to a string, it reads a string.
Specifically it reads the raw character string input
by the user. Thats why its called raw_input()

> stripping a trailing newline) and return it.


> The exercise question is : Can you find other ways to use it?

There are many ways to use it just as there are many ways to use any 
function. But the function will always do the same thing.

For example you can wrap the function in a type conversion to get 
numbers instead of strings:

quantity = int( raw_input("How many? ") )

Or you can use it to pause a program, for example if displaying a text 
file a page/screen at a time, or while debugging.



> Here is the original code from the book:
>
> print  "How old are you?",
> age  =  raw_input()
> print  "How tall are you?",
> height  =  raw_input()
> print  "How much do you weigh?",
> weight  =  raw_input()
> print  "So, you're%r  old,%r  tall and%r  heavy."  %  (
>      age,  height,  weight)

Obviously you can remove the print statements.
And you could convert the height and weight values
to numerical ones (probably floats).

> Now, the only different way I was able to use raw_input is:
>
> age =raw_input("How old are you? ")
> height=  raw_input("How tall are you?")
> weight=  raw_input("How much do you weigh?")
>
> print  "So, you're %r old, %r tall and %r heavy."  %  (age,  height,  weight)

Yes, that would be the normal way to do it, or with type conversion:

age    = int( raw_input("How old are you? ") )
height = float( raw_input("How tall are you?") )
weight = float( raw_input("How much do you weigh?") )

print  "So, you're %d old, %f tall and %f heavy."  %  (age,  height, 
weight)

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list