1

Please I am pretty new to python, I am trying to import a function from a python file A to another python file B. But as soon as I import the file or just the function of the python file A, the entire imported file runs as soon as i run python file B.

# pythonfile A
def email():
        print('Hello how are you doing?')

email()
user = input('Enter response')
print(user)

Running this code I get:

Hello how are you doing?

Enter your response I am good

I am good

# pythonfile B

import pythonfileA
pythonfileA.email()

Running this code I expected to get:

Hello how are you doing?

but I get

Hello how are you doing?

Enter your response I am good

I am good

instead. I also tried another alternative:

# pythonfile B

from pythonfileA import email

email()

Running that code I expected to get:

Hello how are you doing?

but I get

Hello how are you doing?

Enter your response I am good

I am good

Please help me, been searching the internet for solutions but to no good.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Official related docu: [https://docs.python.org/3/library/__main__.html](https://docs.python.org/3/library/__main__.html) and its [usage](https://docs.python.org/3/library/__main__.html#idiomatic-usage) – Patrick Artner Apr 27 '22 at 18:23
  • When you `import` a module, everything in the global scope of that file is executed by the interpreter (all functions/classes are defined, etc). For that reason you should avoid having code in the global scope of a module unless it's either necessary to initialize the other parts of the module or inside a `__main__` block to ensure it only executes when the module is the main script. – Samwise Apr 27 '22 at 18:26

0 Answers0