Table of Contents
How to Print without Parentheses in Python
The upgrade of Python 2 to 3 introduced several critical changes to the existing Python functionality. One such change was done to the print statement.
In Python 2, we used print as a statement. We have seen people stating to use parentheses with print in Python 3. This is because Python 3 changed this to a function. The print() function in Python 3 displays the output and also provides several parameters like sep, end, and more.
We can also create a reference to the print() function in Python 3.
See the code below.
|
1 2 3 4 |
a = print a("Java2Blog") |
Output:
We create a reference a in the above example for the print() function in Python 3.
This tutorial will discuss how to print without parentheses in Python.
Using Python 2
The first method is very obvious, use a Python 2 interpreter. As discussed, Python 2 uses print as a statement so it eliminates the use of parentheses.
For example,
|
1 2 3 |
print "Java2Blog" |
Output:
Using a slash in IPython
Another way to do this is by using the IPython interactive shell. Using this toolkit, we can eliminate the use of parentheses before a function by using a single slash before the function name. It also provides a kernel that is supported by Jupyter notebooks.
We can use a slash with this IDE to print without parentheses in Python.
See the code below.
|
1 2 3 |
/print "Java2Blog" |
Output:
Further reading:
Using the %autocall command in IPython
We can also use the %autocall feature in IPython to call functions without parentheses in Python. Such magic commands need to be used at the start and are executed by the % sign.
With this command, we can print without parentheses in Python. Remember to first execute the command and then use the print() function.
For example,
|
1 2 3 |
%autocall |
Output:
Now we run the print() function without parentheses.
|
1 2 3 |
print "Java2Blog" |
Output:
——> print(“Java2Blog”)
——> print(“Java2Blog”)
Java2Blog
Conclusion
To conclude, we discussed several methods on how to print without parentheses in Python. We highlighted the change to the print statement in the upgrade from Python 2 to Python 3. Python 2 treats print as a statement so we can print without parentheses in Python.
For Python 3 users, there is no direct way to achieve this. The most basic thing we can do is create a reference to the print() function in Python 3 but it will still involve the use of parentheses. The only way to work around this is by using the IPython shell.
The IPython interactive shell provides two ways to print without parentheses in Python. In the first method, we place a single slash before the function. In the second method, we will use the %autocall magic command that allows us to call functions without parentheses in Python.
That’s all about how to print without parentheses in Python