Python Language Basic Usage


Example

Consider the following Python2.x code. Save the file as example.py

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

In the above file, there are several incompatible lines. The raw_input() method has been replaced with input() in Python 3.x and print is no longer a statement, but a function. This code can be converted to Python 3.x code using the 2to3 tool.

Unix

$ 2to3 example.py

Windows

> path/to/2to3.py example.py

Running the above code will output the differences against the original source file as shown below.

RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
RefactoringTool: Refactored example.py
--- example.py    (original)
+++ example.py    (refactored)
@@ -1,5 +1,5 @@
 def greet(name):
-    print "Hello, {0}!".format(name)
-print "What's your name?"
-name = raw_input()
+    print("Hello, {0}!".format(name))
+print("What's your name?")
+name = input()
 greet(name)
RefactoringTool: Files that need to be modified:
RefactoringTool: example.py

The modifications can be written back to the source file using the -w flag. A backup of the original file called example.py.bak is created, unless the -n flag is given.

Unix

$ 2to3 -w example.py

Windows

> path/to/2to3.py -w example.py

Now the example.py file has been converted from Python 2.x to Python 3.x code.

Once finished, example.py will contain the following valid Python3.x code:

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