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--------------
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.
print in Python versions below 3, is not a function. There's a separate print statement which is part of the language grammar. print is not an identifier. It's a keyword.
The deal is that print is built-in function only starting from python 3 branch. Looks like you are using python2.
Check out:
print "foo"; # Works in python2, not in python3
print("foo"); # Works in python3
print is more treated like a keyword than a function in python. The parser "knows" the special syntax of print (no parenthesis around the argument) and how to deal with it. I think the Python creator wanted to keep the syntax simple by doing so. As maverik already mentioned, in python3 print is being called like any other function and a syntx error is being thrown if you do it the old way.
Related
So you can apply a variable amount of arguments from a list to a normal function by doing this
someFunc(*[1,2,3])
But it doesn't work when I used the built-in print
print(*[1,2,3])
^
SyntaxError: invalid syntax
How can I achieve the same effect with print?
The issue is that in python prior to python 3, print is a keyword of the language and not a function, so it doesn't work the same way. If you want to achieve a similar effect you can just make your own print function
def output(*args):
print ' '.join(str(i) for i in args)
then use output(*[1,2,3])
Or if your version of python2 is recent enough (>= 2.6) you can do
from __future__ import print_function
to get the python 3 semantics.
When I am using sep argument in the Python 2.7.3, it is showing error
for example:-
>>>print ("Hello","World",sep ="**")
File "<stdin>", line 1
print ("Hello","World",sep ="**")
^
SyntaxError: invalid syntax
In Python 2.x, unlike in Python 3.x, print is not a function, but a statement described here. Basically it means that print is treated as a keyword (like for) and is not as powerful as the print function that you know from Python 3.x. In particular, it does not support the sep keyword argument.
You can make print behave similarly to Python 3.x by using the following import:
from __future__ import print_function
If you prefer no to use this import, you can achieve the effect you wanted with:
print "**".join(["Hellow", "World"])
You need to type this line first:
from __future__ import print_function
To make print a function, and allow passing arguments like that.
In python everything is an object and you can pass it around easily.
So I can do :
>> def b():
....print "b"
>> a = b
>> a()
b
But if I do
a = print
I get SyntaxError . Why so ?
In Python 2.x, print is a statement not a function. In 2.6+ you can enable it to be a function within a given module using from __future__ import print_function. In Python 3.x it is a function that can be passed around.
In python2, print is a statement. If you do from __future__ import print_function, you can do as you described. In python3, what you tried works without any imports, since print was made a function.
This is covered in PEP3105
The other answers are correct. print is a statement, not a function in python2.x. What you have will work on python3. The only thing that I have to add is that if you want something that will work on python2 and python3, you can pass around sys.stdout.write. This doesn't write a newline (unlike print) -- it acts like any other file object.
print is not a function in pre 3.x python. It doesn't even look like one, you don't need to call it by (params)
I understand what print does, but of what "type" is that language element? I think it's a function, but why does this fail?
>>> print print
SyntaxError: invalid syntax
Isn't print a function? Shouldn't it print something like this?
>>> print print
<function print at ...>
In 2.7 and down, print is a statement. In python 3, print is a function. To use the print function in Python 2.6 or 2.7, you can do
>>> from __future__ import print_function
>>> print(print)
<built-in function print>
See this section from the Python Language Reference, as well as PEP 3105 for why it changed.
In Python 3, print() is a built-in function (object)
Before this, print was a statement. Demonstration...
Python 2.x:
% pydoc2.6 print
The ``print`` statement
***********************
print_stmt ::= "print" ([expression ("," expression)* [","]]
| ">>" expression [("," expression)+ [","]])
``print`` evaluates each expression in turn and writes the resulting
object to standard output (see below). If an object is not a string,
it is first converted to a string using the rules for string
conversions. The (resulting or original) string is then written. A
space is written before each object is (converted and) written, unless
the output system believes it is positioned at the beginning of a
line. This is the case (1) when no characters have yet been written
to standard output, (2) when the last character written to standard
output is a whitespace character except ``' '``, or (3) when the last
write operation on standard output was not a ``print`` statement. (In
some cases it may be functional to write an empty string to standard
output for this reason.)
-----8<-----
Python 3.x:
% pydoc3.1 print
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
print is a mistake that has been rectified in Python 3. In Python 3 it is a function. In Python 1.x and 2.x it is not a function, it is a special form like if or while, but unlike those two it is not a control structure.
So, I guess the most accurate thing to call it is a statement.
In Python all statements (except assignment) are expressed with reserved words, not addressible objects. That is why you cannot simply print print and you get a SyntaxError for trying. It's a reserved word, not an object.
Confusingly, you can have a variable named print. You can't address it in the normal way, but you can setattr(locals(), 'print', somevalue) and then print locals()['print'].
Other reserved words that might be desirable as variable names but are nonetheless verboten:
class
import
return
raise
except
try
pass
lambda
In Python 2, print is a statement, which is a whole different kind of thing from a variable or function. Statements are not Python objects that can be passed to type(); they're just part of the language itself, even more so than built-in functions. For example, you could do sum = 5 (even though you shouldn't), but you can't do print = 5 or if = 7 because print and if are statements.
In Python 3, the print statement was replaced with the print() function. So if you do type(print), it'll return <class 'builtin_function_or_method'>.
BONUS:
In Python 2.6+, you can put from __future__ import print_function at the top of your script (as the first line of code), and the print statement will be replaced with the print() function.
>>> # Python 2
>>> from __future__ import print_function
>>> type(print)
<type 'builtin_function_or_method'>
Ok, this is funny.
>>> exec("print")
>>> help(exec)
File "<stdin>", line 1
help(exec)
^
SyntaxError: invalid syntax
>>>
looks like exec is a statement, not a function, hence you cannot help() it. Is this expected or a bug? if expected, why? can you reproduce it on python3 ? I have Python 2.6.1 here.
In Python 2.x, exec is a statement (and thus doesn't have a docstring associated with it.)
In Python 3.x, exec is now a function: http://docs.python.org/py3k/library/functions.html?highlight=exec#exec
So it can (and does) have a docstring.
You'd get this same behavior for help(print), which also became a function in 3.x.
yes, like my followers said but for me i usually do :
>>> help("exec")
>>> help("print")
and it work for python 2.* and python 3k
Just put quotes around it (works for assert, etc. too):
>>> help('exec')
http://docs.python.org/release/3.0.1/library/functions.html#exec
In Python 3, exec() is a function. Apparently, in Python 2, exec is a statement but can be used similarly to a function.
http://docs.python.org/release/3.0.1/whatsnew/3.0.html#removed-syntax
Removed keyword: exec() is no longer a keyword; it remains as a function. (Fortunately the function syntax was also accepted in 2.x.)