Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python's print function not exactly an ordinary function?

Tags:

python

Environment: python 2.x

If print is a built-in function, why does it not behave like other functions ? What is so special about print ?

-----------start session--------------
>>> ord 'a'
Exception : invalid syntax
>>> ord('a')
97
>>> print 'a'
a
>>> print('a') 
a
>>> ord
<built-in function ord>
>>> print

-----------finish session--------------
like image 399
Frankie Ribery Avatar asked Dec 08 '25 10:12

Frankie Ribery


1 Answers

The short answer is that in Python 2, print is not a function but a statement.

In all versions of Python, almost everything is an object. All objects have a type. We can discover an object's type by applying the type function to the object.

Using the interpreter we can see that the builtin functions sum and ord are exactly that in Python's type system:

>>> type(sum)
<type 'builtin_function_or_method'>
>>> type(ord)
<type 'builtin_function_or_method'>

But the following expression is not even valid Python:

>>> type(print)
SyntaxError: invalid syntax

This is because the name print itself is a keyword, like if or return. Keywords are not objects.

The more complete answer is that print can be either a statement or a function depending on the context.

In Python 3, print is no longer a statement but a function.

In Python 2, you can replace the print statement in a module with the equivalent of Python 3's print function by including this statement at the top of the module:

from __future__ import print_function

This special import is available only in Python 2.6 and above.

Refer to the documentation links in my answer for a more complete explanation.

like image 57
Iain Samuel McLean Elder Avatar answered Dec 10 '25 01:12

Iain Samuel McLean Elder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!