tags:

views:

363

answers:

4

How can I implement the following in python?

#include <iostream>

int main() {
   std::string a; 
   std::cout <<  "What is your name? ";
   std::cin >> a; 
   std::cout << std::endl << "You said: " << a << std::endl;
}

Output:

What is your name? Nick

You said: Nick

+3  A: 

Look at the print statement and the raw_input() function.

Or look at sys.stdin.read() and sys.stdout.write().

When using sys.stdout, don't forget to flush.

S.Lott
+7  A: 

Call

name = raw_input('What is your name?')

and

print 'You said', name
Swaroop C H
You might want to do "name.rstrip()" or just "name.strip()" to remove whitespace.
monkut
Feel free to post that as an answer and i'll upmod it
Nick Stinemates
+3  A: 
print "You said:", raw_input("What is your name? ")

EDIT: as Swaroop mentioned, this doesn't work (I'm guessing raw_input flushes stdout)

orip
This would print "You said What is your name?"
Swaroop C H
@Swaroop: You're right, my bad :)
orip
+1  A: 

The simplest way for python 2.x is

var = raw_input()
print var

Another way is using the input() function; n.b. input(), unlike raw_input() expects the input to be a valid python expression. In most cases you should raw_input() and validate it first. You can also use

import sys
var = sys.stdin.read()
lines = sys.stdin.readlines()
more_lines = [line.strip() for line sys.stdin]

sys.stdout.write(var)
sys.stdout.writelines(lines+more_lines)
# important
sys.stdout.flush()

As of python 3.0, however, input() replaces raw_input() and print becomes a function, so

var = input()
print(var)
Alex R