1

When I am importing a function from a module into a script of another file and then run it, the function starts all over after it has finished although it is supposed to run only once.

If I, however, only run the cell with the imported function then the function sometimes only runs once which is confusing because I have deactivated everything else in the script so it should not make a difference, should it? But sometimes it also runs twice which is even more confusing because I have not changed anything in the meantime (at least not that I would know).

One difference is that when I run the entire script the console says

Reloaded modules: mytestmodule

after the script has been executed while when I only run the cell this does not show up. I do not know if this matters though.

Either way, here is the function (from the file mytestmodule.py):

def equation():
    
    print("Hi! Please enter your name.")
    name=input()
    
    print("Hello "+name+"! Please enter an integer that is bigger than 1 but smaller than 10.")
    
    answertrue="That is correct!"
    answerfalse="That integer is not correct. Please try again."
    answernointeger="That is not an integer. Please try again."

    biggersmaller=True
    while biggersmaller:
        task=input()
        try:
            if int(task)>1 and int(task)<10:
                return(print(answertrue))
                break
            else:
                print(answerfalse)
        except ValueError:
            print(answernointeger)
equation()

And here is the script of the import in the other file:

import mytestmodule
mytestmodule.equation()
Brian61354270
  • 8,690
  • 4
  • 21
  • 43
Beinhaus
  • 11
  • 2
  • 1
    When you import a module, everything at the base level is executed. You have a call to `equation` there. You also have one just after the `import`, so it's going to be called twice. – Mark Ransom Aug 05 '21 at 00:48
  • 1
    You may be interested in [What does `if __name__ == "__main__":` do?](https://stackoverflow.com/questions/419163/what-does-if-name-main-do) – Brian61354270 Aug 05 '21 at 00:50
  • @Brian Thank you, that worked! Edit: Also that were some fast answers, wow! – Beinhaus Aug 05 '21 at 01:18

1 Answers1

0

This is because inside your mytestmodule.py you are calling the equation function already. Either:

  1. Remove the call of equation from mytestmodule.py
  • or
  1. Don't call the function after importing it
pu239
  • 707
  • 7
  • 17