The external file I am importing is running instead of the main file it is being imported to

Advertisements

I have imported a external file that I have made into another program I have made. Here is the code: from Number_guesser.Number_guesser_main import start_number_guesser.
However instead of the main file itself running normally and giving the first input question of the main file. (This) ans1 = typing_with_user_input_main_program("\nWelcome to Minigame land! Would you like to play? (Y/N) "). I am instead being given the fist input line form the imported external file. (This) ans1 = typing_with_user_input(f"\nHello! Would you like to play the number guessing game? (Y/N) ")

I am fairly new to python and have tried for a few days to try and fix the problem but nothing seems to be working. Can someone help me fix the problem?

I have tried moving the external file to make the import statement less complex, using sys to change to path to the external file, importing just the external file and not the specific subroutine I want to use.

However non of these have had any impact on the error.

>Solution :

When you import a module, all of the "top-level" code in that module will executed.

So, if a module has print() or input() statements at the top level, i.e. not indented underneath a class or function definition, then those statements will execute, and you will see that output on the console.

If you have some code that you do not want to be executed when the module is imported, then you need to "hide" that code inside an if statement that looks like this:

if __name__ == '__main__':
    print('This message will only appear when this module is ')
    print('executed directly, and not when this module is imported.')

Leave a ReplyCancel reply