This is the biggest newbie question on the planet, but I'm just not sure. I've written a bunch of functions that perform some task, and I want a "main" function that will, for example, when I call "someProgram.py", run function1, function2 and quit. I vaguely remember something about "main" but I have no clue.
Python scripts are not collections of functions, but rather collections of statements - function and class definitions are just statements that bind names to function or class objects.
If you put a print statement at the top or middle of your program, it will run normally without being in any function. What this means is that you could just put all the main code at the end of the file and it will run when the script is run. However, if your script is ever imported rather than run directly, that code will also run. This is usually not what you want so you would want to avoid that.
Python provides the __name__
global variable to differentiate when a script is imported and run directly - it is set to the name under which the script runs. If the script is imported, it will be the name of the script file. If it is run directly, it'll be "__main__"
. So, you can put an if __name__ == '__main__':
at the bottom of your program, and everything inside this if block will run only if the script is run directly.
Example.
if __name__ == "__main__":
the_function_I_think_of_as_main()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With