#๐Ÿ”’ This Output Prediction Question !

10 messages ยท Page 1 of 1 (latest)

vital remnant
#

Hello, Could someone pls explain the logic of this code and its output???

tall whaleBOT
#

@vital remnant

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

lavish widget
# vital remnant Hello, Could someone pls explain the logic of this code and its output???

funcs = []
this is a list, it is currently empty however

for i in range(3): # counts from 0 - 2 (0, 1, 2) -> That's 3 numbers!
    def f():
        return i # returns i, which is a number
    funcs.append(f) # add the function 'f' to the list
````funcs` should now have 3 `f`s in it

```py
for fn in funcs: # Iterate through the list, i.e go through each element in the list
  print(fn()) # 'fn()' calls the function, then we print what the function returns
vital remnant
lavish widget
#

imagine this,

for fn in funcs: # Iterate through the list, i.e go through each element in the list
  print(fn()) # 'fn()' calls the function, then we print what the function returns

is the same as

fn()
fn()
fn()

And since fn does return i and previously we looped all the way until 2, it will always output 2

TLDR; we aren't storing the value of i, we are storing the variable, and that variable has a value of 2 at the end of the for i in range(3) loop

light shell
#

wait I got a bit confused with appending f instead of f()

light shell
# vital remnant Hello, Could someone pls explain the logic of this code and its output???

your appending the function object to the list. As you are appending outside the function the maximum value of i is appended but you didn't call the function. the function object that returns 2 is appended. In the second loop when you iterate through the list. you are calling the function object which is returning the value 2 as the other values through the loop are not stored which is why you see only twos instead of 0, 1, 2

#

if you wanted 0,1,2 then you would append i inside the function

tall whaleBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.