Search Placementyogi.com
 

Convert Python2.x code to 3.x | print Error and urllib2 error in python 3.x

You might have got this error :

print"Hey" SyntazError: invalid syntax

 

If yes , the reason is that you are trying to run a python 2.x code on python 3.x interpreter.

Python 3.x implements print as a method while python 2.x has it as a statement.

Solution:

Lets consider that the file name is sample.py

You can solve it in 2 ways,

1. Install a python 2.x interpreter and then run the sample.py like this:(On Windows)

    C:\Python27\python.exe sample.py

    i.e. point to the python2.x version of interpreter and run it .

2. Convert your code to python3.x using 2to3.py :

   You can refer: https://docs.python.org/2/library/2to3.html.

Here is a sample Python 2.x source file, example.py:

def greet(name):
    print "Hello, {0}!".format(name)
print "What's your name?"
name = raw_input()
greet(name)

It can be converted to Python 3.x code via 2to3 like this :

$ 2to3 -w example.py

Preview

Thanks for posting your comment! It will be visible soon!
Post Another Comment

4
+
1
=

Name:
Email :
Banner to LogicGuns.com

Hide Page Information