
Does this mean I can't write code that runs on both Python 2 and Python 3?
No, you can, of course, write your code in Python 2.x and make it compatible with both versions, but you will need to import a few libraries first, such as the __future__ module, to make it backward compatible. This module contains some functions that tweak the Python 2.x behavior and make it exactly like Python 3.x. Take a look at the following examples to understand the differences between the two versions:
#python 2 only
print "Welcome to Enterprise Automation"
The following code is for Python 2 and 3:
# python 2 and 3
print("Welcome to Enterprise Automation")
Now, if you need to print multiple strings, the Python 2 syntax will be as follows:
# python 2, multiple strings
print "welcome", "to", "Enterprise", "Automation"
# python 3, multiple strings
print ("welcome", "to", "Enterprise", "Automation")
If you try to use parentheses to print multiple strings in Python 2, it will interpret it as a tuple, which is wrong. For that reason, we will import the __future__ module at the beginning of our code, to prevent that behavior and instruct Python to print multiple strings.
The output will be as follows:
