-2

This is a main file in which I start an other.py script. The initial import works, it executes the other.py on line 1.

But when this has ran the other.py, it will ask input to to restart other.py once more. The 'no' answer is working, the 'yes' answer just keeps giving me the same prompt.

So the import is not working in my if statement. Any ideas please?

import other

while True:
    prompt = input("Restart? Yes / No: ")
    if prompt == "yes" or prompt == "Yes":
        import other
    elif prompt == "no" or prompt == "No":
        print("Goodbye!")
        break
  • 2
    Wrap the code in "other" in a function and call that function. Imported modules are stored in a cache and aren't executed a second time. There are ways to force another execution but it shouldn't be done. – Michael Butscher Oct 24 '22 at 08:16
  • 4
    `import` does not mean *"run the code in the other module now"*. It just makes the other module available as a name. Its code will only be executed once on initially loading it. The import mechanism isn't the right tool to execute reusable code. Functions are. – deceze Oct 24 '22 at 08:19
  • 1
    BTW, what if I type "YES"? Why allow "yes" but not "YES"? (Hint: generalise this and lowercase the input, so you don't need to test for randomly capitalised versions.) – deceze Oct 24 '22 at 08:21
  • hi, check this if you are trying to reload (re import) a module https://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module – BlueBeret Oct 24 '22 at 08:24
  • @deceze adjusted with lower(), thanks for the tip – Kevin Provoost Oct 24 '22 at 08:41

1 Answers1

0

Once python has imported a module it won't import it again. You have to specifically ask python to reload a module if you want it to reload it.

Try and remove the import other from the top and run your app.

Michael Wiles
  • 20,902
  • 18
  • 71
  • 101