Question

I have the following code:

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)

Ok so the raw_input function can standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

What I don't understand is why every prompt message is presented on a new line since raw_input only returns a string. It doesn't add a newline and I don't have any \n in the code.

Was it helpful?

Solution

When you type a response to the raw_input() you finish by entering a newline. Since each character you enter is also displayed as you type, the newline shows up as well.

If you modified the python builtins and changed raw_input you could get it to terminate on '.' instead of '\n'. An interaction might look like: How old are you? 12.How tall are you? 12.How much do you weigh? 12. So you're ...

OTHER TIPS

Here is a way to do it in windows, using msvcrt. You could do a similar thing on Mac or unix using curses library.

import msvcrt
import string

print("How old are you? "),
age = ''
key = ''
while key != '\r':
    key = msvcrt.getch()
    age += key
print("How tall are you? "),
key = ''
height = ''
while key != '\r':
    key = msvcrt.getch()
    height += key
print("How much do you weigh? "),
key = ''
weight = ''
while key != '\r':
    key = msvcrt.getch()
    weight += key
print "\n So, you're %r old, %r tall and %r heavy." %(string.strip(age), string.strip(height), string.strip(weight))

Sample output looks like this:

How old are you?  How tall are you?  How much do you weigh?
 So, you're '37' old, "6'" tall and '200' heavy.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top