Efe Büyük
Efe Büyük

Reputation: 145

How to get input in Python 2.7?

First, let me share my simple code;

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys

print ("test")

var = raw_input("Enter your words: ")
print ("Your words: "), var

What I expect when I run this code is that first, "test" text will appear on the screen, then "Enter your words: " text will appear and wait for my input. After I enter my input, it will also show my input on the screen with the last print command.

However, what I get when I run this code is that it waits for an input first, then after I give my input value, It shows all values respectively. It writes "test" first, then my input value on the screen.

Can you help me for solving this issue? Thank you.

Upvotes: 0

Views: 307

Answers (1)

dot.Py
dot.Py

Reputation: 5157

You're using a print statement from python 3+ with python 2+.

According to the What's new in Python 3.0, you can see that the print method is now a function.

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!

Python 2+:

print "test"

Python 3+:

print("test")

Fixed Code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys

print "test"

var = raw_input("Enter your words: ")
print "Your words: ", var

Output of the fixed code:

anon@anon-pc:~/Desktop$ python test.py

test

Enter your words: itsWorking

Your words: itsWorking

anon@anon-pc:~/Desktop$

Upvotes: 2

Related Questions