# Re: Learn Python the Hardway exercise 11 question 4

Discussion in 'Python' started by eryksun (), Mar 31, 2011.

1. ### eryksun ()Guest

On Wednesday, March 30, 2011 11:03:09 PM UTC-4, JosephS wrote:
> 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)
> Note:
> Notice that we put a , (comma) at the end of each print line. This is
> so that print doesn’t end the line with a newline and go to the next
> line.
> What You Should See
> Extra Credit
> 1. Go online and find out what Python’s raw_input does.
> \$ python ex11.py How old are you?
> 35 How tall are you?
> 6'2" How much do you weigh? 180lbs
> So, you're '35' old, '6\'2"' tall and '180lbs' heavy.
>
> Related to escape sequences, try to find 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?

There appears to be a formatting error here. The following works:

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)

Regarding the escape sequence, your're using %r which shows the representation (repr) of the string. For example:

In [1]: [x for x in height]
Out[1]: ['6', "'", '2', '"']

In [2]: print height
6'2"

In [3]: [x for x in repr(height)]
Out[3]: ["'", '6', '\\', "'", '2', '"', "'"]

In [4]: print repr(height)
'6\'2"'

The characters stored in height are just 6'2", but you couldn't input the string like that as a variable since Python uses quotes to demarcate a string literal. The backslash escapes the quote so that the interpreter will treat it as a regular character. It's unnecessary to escape the double quote, on the other hand, since this string literal is marked with single quotes. If the string were instead inputted with double quotes, then the final double quote would have to be escaped, such as the following: height = "6'2\"". Finally, notice that in the output representation of the characters of repr(height) (Out[3]) that the backslash itself has to be escaped. Otherwiseit would be interpreted as escaping the single quote that follows.

eryksun (), Mar 31, 2011