Have you wondered why sometimes you see Python code where print is called without parenthesis?
print "This is a test"
Calling print without parenthesis is actually possible only in Python 2.
In Python 3 it is no longer possible to print without parenthesis.
The reason why is because print used to be a statement in Python 2. In Python 3 print() is a function. As you know, a function call always requires parenthesis.
How to Save Time with print() Function
Iin Python 3 you need parenthesis when printing.
If you find it time-consuming to write print() with parenthesis, there is a little time saver trick you can use. Before showing it, please keep in mind this is not recommended as it makes your code less readable.
The trick to saving time when writing print() is by creating a shorthand for it.
To do this, assign the print function to a variable with a short name.
For instance:
p = print p("Hello world")
Output in the console:
Hello world
This works because the variable p now points to the same memory address as the print function. This makes it an alias of the print function.
Conclusion
Today you learned why printing without parenthesis is not possible in Python 3.
To recap, in Python 3, print is a function, not a statement like in Python 2.x. This means you need to call it with parenthesis.
Although not recommended, you can create a short alias for the print function to save keystrokes.
Thanks for reading. I hope you find it useful.
Happy coding!
Further Reading
How to Write to a File in Python
About the Author
- I'm an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
Recent Posts
Artificial Intelligence2023.05.16Humata AI Review (2023): Best PDF Analyzer (to Understand Files)
Python2023.05.139 Tips to Use ChatGPT to Write Code (in 2023)
Artificial Intelligence2023.04.1114 Best AI Website Builders of 2023 (Free & Paid Solutions)
JavaScript2023.02.16How to Pass a Variable from HTML Page to Another (w/ JavaScript)