3

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

4 Answers 4

7

Call

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

and

print 'You said', name
Sign up to request clarification or add additional context in comments.

2 Comments

You might want to do "name.rstrip()" or just "name.strip()" to remove whitespace.
Feel free to post that as an answer and i'll upmod it
3

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.

Comments

3
print "You said:", raw_input("What is your name? ")

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

1 Comment

This would print "You said What is your name?"
1

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)

Comments

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.