470,604 Members | 2,065 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,604 developers. It's quick & easy.

How come print cannot be assigned to a variable?

Hi all,
In Python, some functions can be assigned to variables like this:
length=len
Why is it that print cannot be assigned to a variable like this? (A
syntax error is declared.)

Thanks,

Vaibhav

Jul 19 '05 #1
4 1439
print is a statement, not a function.

Read Guido's words on that:
http://www.python.org/search/hyperma...1992/0112.html

Regards.
Adriano.
Jul 19 '05 #2
Thank You Adriano. You were a huge help.

Vaibhav

Jul 19 '05 #3
an***********@gmail.com wrote:
Hi all,
In Python, some functions can be assigned to variables like this:
length=len
Why is it that print cannot be assigned to a variable like this? (A
syntax error is declared.)

Thanks,

Vaibhav


print can't be assigned to variables since it's not a funcion, it's part
of the syntax of the language, like `for', `while', etc. and it can't be
assigned to variables, just as those can't be assigned.
If you need a function that prints stuff, consider these two examples:
[snip]
PrintFunc = lambda x: print x
[snip]
Or, a somewhat better solution:
[snip]
import sys
PrintFunc = sys.write
[snip]
Jul 19 '05 #4
John Doe wrote:
If you need a function that prints stuff, consider these two examples:
[snip]
PrintFunc = lambda x: print x


py> printfunc = lambda x: print x
Traceback ( File "<interactive input>", line 1
printfunc = lambda x: print x
^
SyntaxError: invalid syntax

See Inappropriate use of Lambda on the Python Wiki[1]. This is also a
horrible idea as it means you can only print a single item:

py> print 1, 2, 3
1 2 3
py> def write(x):
.... print x
....
py> write(1, 2, 3)
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: write() takes exactly 1 argument (3 given)
py> def write(*args):
.... print args
....
py> write(1, 2, 3)
(1, 2, 3)

The print statement has special spacing behavior. You could perhaps
approximate it with something like:

py> def write(*args):
.... for arg in args:
.... print arg,
.... print
....
py> write(1, 2, 3)
1 2 3

But why go to all this effort?

STeVe

[1] http://wiki.python.org/moin/DubiousPython
Jul 19 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

19 posts views Thread by Karl Scalet | last post: by
23 posts views Thread by stewart.midwinter | last post: by
2 posts views Thread by Trevor Davies | last post: by
10 posts views Thread by Tony K | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.