In the following .py program, n
is used within countingFunc
but doesn't have to be included among its arguments, because, we might say, "n
doesn't change."
n = 6
k = 0
def countingFunc(k):
if k < n:
k += 1
print(k)
else:
k = n
countingFunc(k)
However, there can be many ways in which a variable may or may not change in the functions of a module. For simple cases that include expressions that change n
but that could never execute (like below), the compiler complains that n
is referenced before it is assigned.
n = 6
k = 0
def countingFunc(k):
if k < n:
k += 1
print(k)
else:
k = n
if k > n:
print('A miracle has occurred')
n += 1
countingFunc(k)
This raises the question of what criterion the compiler uses to determine whether a variable can be omitted from the arguments of a function. (Since we want code to be portable across compilers, I would imagine that this criterion is the same or very similar for most compilers, but this is just a guess.)
With the exception of cracking open compiler source code, I've dug through online resources looking for an answer but without success. There are good tutorials on passing variables like this one and this one, and there is interesting information in the answers of related Stack Overflow questions such as this one. However, I'm still looking for a direct answer to the above question.
NOTE: As mentioned by furas (B. Burek) in the comments, best practice in Python (and many other languages) is to explicitly include all used variables as arguments and not omit them. This question merely observes that standard Python interpreters do allow certain variables to be omitted from function arguments according to some criterion and asks what this criterion is.