3

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.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
0101amt
  • 2,438
  • 3
  • 23
  • 21
  • 8
    When you enter the input, do you press the Enter key when you are done? – murgatroid99 Oct 18 '11 at 18:39
  • @murgatroid99: True, although one might think, as Enter "sends" the input to the application, that it is not part of the input anymore... but well... it is. – Felix Kling Oct 18 '11 at 18:44
  • Is what you are looking for is to have all the prompts on the same line? raw_input can't do that. You could try curses or msvcrt on windows. – jgritty Oct 18 '11 at 18:49
  • @murgatroid99 Like Felix Kling said, I thought Enter is not part of the input. Seems like I was wrong. Thanks for pointing this out to me. – 0101amt Oct 18 '11 at 18:50

2 Answers2

4

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 ...

Vasiliy Sharapov
  • 997
  • 1
  • 8
  • 27
1

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.
jgritty
  • 11,660
  • 3
  • 38
  • 60
  • You could have it echo back the characters to the screen as well, but notice it's not outputting the user's input until the end. – jgritty Oct 18 '11 at 19:01