Python | Conditional Main Program

Code example
Code example

Today I learned about the use of a “conditional main program” when programming Python. I read about this in a great Python tutorial PDF from Southampton Uni.

You may write some code that is only intended to be used as a module for another program. So if you try running the module directly you may well get no output or response. But, if you include the code below

if __name__ == " __main__ " :

and if you include some functionality to this function, you will get some handy output. It means you can run a module as its own program. You could get it to give some instructions about the correct use of the actual program or use it as an example of what the main program is supposed to do.

Go to page 73 of the PDF for a better explanation! Or this blog post about the same topic.

And here is a page about Spyder and part of a book on computational programming that also covers Spyder.

Published by


Maths Tutor - Computer Musician - Web Developer ...... Parent