__future__ module with print_function
Example 1:
The Python2 print statement is different from Python3 print function. We use the Python print statement in Python2 as:
print "Hello world"
But we can use the Python3 print function in the Python2 function using the future modules.
Python
# Code in Python 2 from __future__ import print_function print ( "Hello world" ) |
Output:
Hello world
Example 2:
Here we are going to print the message in Python 2.X with end attributes that come in Python 3 and “end” appends string in a newline. And it will raise an error because the function is not compatible with 2.x.
Python
# In 2.7 python compiler print ( "Hello world" , end = " " ) |
Output:
File "main.py", line 1 print("Hello world", end=" ") ^ SyntaxError: invalid syntax
So with __future__ print function we can import these features in our code to use the latest print function.
Python
# In 2.7 python compiler from __future__ import print_function print ( "Hello world" , end = ";" ) |
Output:
Hello world;
Example 3:
sep also belongs to Python 3.x but here we will use these attributes by using this module. Let’s check these attributes without using the future modules.
Python3
# In 2.7 python compiler print ( 'Welcome ' , ' w3wiki' , sep = ' To ' ) |
Output:
File "main.py", line 1 print('Welcome ', ' w3wiki', sep=' To ') ^ SyntaxError: invalid syntax
Then let’s use the __future__ print function to use the sep attributes.
Python
# In 2.7 python compiler from __future__ import print_function print ( 'Welcome ' , ' w3wiki' , sep = ' To ' ) |
Output:
Welcome To w3wiki
__future__ Module in Python
__future__ module is a built-in module in Python that is used to inherit new features that will be available in the new Python versions..
This module includes all the latest functions which were not present in the previous version in Python. And we can use this by importing the __future__ module. Its releases are in Python version 2.1. The basic idea of the __future__ module is to help migrate to use Python 3.X features.
Note: The future statements must at the top of the file, otherwise the Python interpreter will raise SyntaxError