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.

4
  • 8
    When you enter the input, do you press the Enter key when you are done? Commented Oct 18, 2011 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. Commented Oct 18, 2011 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. Commented Oct 18, 2011 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. Commented Oct 18, 2011 at 18:50

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.