I am having difficulty importing a function from another script. Both of the scripts below are in the same directory. Why can't the function from another script handle an object with the same name (arr)?
evens.py
def find_evens():
return [x for x in arr if x % 2 == 0]
if __name__ == '__main__':
arr = list(range(11))
print(find_evens())
import_evens.py
from evens import find_evens
if __name__ == '__main__':
arr = list(range(11))
print(find_evens())
Traceback
Traceback (most recent call last):
File "C:\Users\user\Desktop\import_evens.py", line 7, in <module>
find_evens()
File "C:\Users\user\Desktop\evens.py", line 2, in find_evens
return [x for x in arr if x % 2 == 0]
NameError: name 'arr' is not defined
from .evens import find_evensarrin as a function argument instead, and definefind_evensto take a parameter (e.g.def find_evens(arr): ...and calling it withfind_evens(arr))arrdoesn't get defined inevens.pywhen it is being imported (because then it's not__main__). And it won't see thearrdefined inimport_evens.py.