Importing and executing a local function in python

Question:

So I’m trying to complete some of the project Euler challenges in Python3.6 and I’ve run into this problem:

def divisors(n):
    divisors = []
    for i in range(2, round(n/2)+1):
        if n%i == 0:
                divisors.append(int(n/i))
    divisors.append(1)
    return sum(divisors)

def checkAmicable(n):
    if divisors(divisors(n)) == n:
        if divisors(n) != n:
            return True
    else:
        return False

def main():
    amicables = []
    for i in range(1,20000):
        if checkAmicable(i) == True:
            if (divisors(i)+i) not in amicables and divisors(i)<10000:
                amicables.append(divisors(i)+i)
    print(sum(amicables))

main()

This is my solution to problem 21 (euler21.py), it works and gives the sum of the amicable pairs as asked. I want to be able to import the function “divisors(n)” into another file of code (in this case euler23.py).

From my understanding this should work:

from euler21 import divisors
print(divisors(220))

And this should simply print 284, however, when executing it, the entire euler21 code executes and I get the results of that program, plus the 284 at the end, like this:

31626
284

Any suggestions? Could it be due to me using my command line as opposed to the IDE?

TL;DR: imported file executes entire code, not the specifically called function.

Asked By: beeves

||

Answers:

When Importing, code is executed so main() is invoked. Use the following:

if __name__ == '__main__':
    main()

This will prevent main() being executed on import

user@PC:~$ cat ./tester.py
def test():
    print('TEST FUNCTION')

if __name__ == '__main__':
    test()
user@PC:~$ python ./tester.py
TEST FUNCTION
user@PC:~$ python
>>> from tester import *
>>> test()
TEST FUNCTION
>>>
Answered By: Kind Stranger
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.