(Mar-04-2018, 05:44 PM)Robo_Pi Wrote:def my_method(): return 0 # it's not necessary but you can do it if __name__ == '__main__': import sys sys.exit(my_method())However if I were to modify this code as follows it should never run at all, right?
This will run just fine.
When the python code runs as a program "__main__" string is assigned to the __name__ special variable.
If the same code is imported as a module, __name__ will contain the name of the module. Any .py file can be imported as a module.
The
if __name__ == "__main__":
statement is a convention in the Python coding. It checks if the file is running as a program, not imported as a module and if that is the case the code block is executed.This is why the most of the python programmers are defining a main() function so if someone else looks at the code he/she knows what it contains. The code to run the file as a program.
Because this became almost standard in the Python coding most of the IDE programs generate it as a template.