Python Print without Parenthesis

How to print without parenthesis in Python

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

Python Tricks

How to Write to a File in Python

The with Statement in Python

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.