Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning print function to variable

Tags:

python

For the following code, it seems to me that we are assigning the print function to the variable, spam.

spam = print('Hello!')

I'm wondering why doesn't calling spam, print out "Hello!"?

like image 618
lagrangian_headache Avatar asked Jan 20 '26 15:01

lagrangian_headache


1 Answers

Because spam isn't a function, it's the result of calling the function print with the argument 'Hello!', which is None, of type NoneType.

If you want to assign that expression to a variable, then you can use a lambda:

l = lambda: print('Hello!') # Doesn't actually call print
l() # 1. Prints 'Hello!'
l() # 2. Prints 'Hello!'
l() # 3. Prints 'Hello!'
like image 95
Alexander Avatar answered Jan 23 '26 05:01

Alexander



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!