wtfpython
wtfpython copied to clipboard
Calling the function without calling it
â–¶ Calling the function without calling it
Make a file test.py Add the following code
def print_HelloWorld():
print("Hello World")
print_HelloWorld()
print("Hello")
Make another file called try.py Add the following code and then run this file
import test
Output
Hello World Hello
See without even calling the function we get the ouput.
💡 Explanation:
This is the magic of import statement in python. Whenever we import a file all the code that is outside of main runs. This is why whatever we write in test.py it will run in when we are importing the file to any other program. To overcome this, we use:
if __name__=='_main__':
and then write everything in the main function. This will stop running the code that is in the imported file.
We can change the test.py file to
def print_HelloWorld():
print("Hello World")
if __name__=="__main__":
print_HelloWorld()
print("Hello")
Output
>>>
Now we get the desired result and nothing is called when we import the test.py file.
I don't really understand this one, you are literally calling a function here

I don't really understand this one, you are literally calling a function here
Actually, I am not running this file. I ran another file in which this file is imported and this code executes automatically.
Actually, I am not running this file. I ran another file in which this file is imported and this code executes automatically.
That is absolutely expected behaviour. Code is executed upon import.
Exactly. And the output goes to the main file's sys.stdout, not anywhere else (and if the imported file changes it , it also affects the main file)