Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does foo = function() run the function in Python?
    primarykey
    data
    text
    <p>I'm up to Exercise 41 in Learn Python the Hard Way, and I'm having a really hard time wrapping my brain around the fact that the entire thing hinges on a function running just because it's been assigned as a value to a variable. I wrote up a little script to confirm that this is how it works, and it does: </p> <pre><code>def pants(): print "Put on some pants!" def shorts(): print "And don't forget your underwear!" zap = pants() thing = shorts() </code></pre> <p>With the results being: </p> <pre><code>Put on some pants! And don't forget your underwear! </code></pre> <p>So obviously this happens, but I can't understand why the language works that way -- what the logic is behind the language that makes this a valuable way of operating. I think it'd be helpful for me moving forward to understand <em>why</em> this is, rather than just "that's the way it works." </p> <p>For clarity: I'm asking (I guess) why the function is running, when all I'm doing is assigning it as a value for something. The print statements are just there so I can see that the function is indeed running. </p> <p>It's the fact that I'm not ever actually running </p> <p>pants() shorts() </p> <p>that is confusing me.</p> <p>To create a tortured analogy, if me-baking-cookies-at-home were "cookies()", and I were to make cookies on Saturdays, I might eventually believe that </p> <p>Saturday = cookies()</p> <p>but just thinking "hey, Saturday is cookie day" is not the same as <em>actually baking cookies</em>... so why does just saying</p> <p>Saturday = cookies() </p> <p>actually bake the cookies, rather than just setting up Saturday with the variable "cookies()" for some later use? </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload