-4
def fi(n):
    print(counter)
    data = counter + 1
    return data


counter = 2
print(fi(10))

How can this code work well?? I guess this code doesn't work well because of counter in fi()function, there's no declaration of counter...

Chrᴉz remembers Monica
  • 1,829
  • 1
  • 10
  • 24
  • 2
    `counter` will look for a local variable, if it doesn't find one, it looks for the variable in any enclosing scopes, then finally, in the global scope. So yes, this will work. – juanpa.arrivillaga Jan 08 '20 at 12:34
  • 1
    shouldn't you you substitute `counter` for `n`? – Stefan Jan 08 '20 at 12:35
  • 1
    What is the purpose or context of this function/code? Are you intending that `fi` increases the counter by 1 regardless of the value of `n`? Were you meaning to increase it by `n`? Were you intending to use `n` at all? – PyPingu Jan 08 '20 at 12:37
  • thank you ~~~ i catch it – YoonSik Jan 08 '20 at 12:44

1 Answers1

0

You are mis-using the counter variable; to keep your function pure, just use n in the function, e.g.:

def fi(n):
    print(n)
    data = n + 1
    return data


counter = 2
print(fi(counter))
Stefan
  • 17,448
  • 11
  • 60
  • 79
  • i know i'm misusing but a point is counter can work well even if there's no declaration in fi()function – YoonSik Jan 08 '20 at 12:38
  • So, if it's out of scope you cannot use it; if it's in scope; you can use it. If you want to change it assign the output of the function to the variable: this is how it works. – Stefan Jan 08 '20 at 15:29