Jump to content

First Time Writing Python Programs

- - - - -

  • Please log in to reply
1 reply to this topic

#1
restin84

restin84

    Learning Programmer

  • Members
  • PipPipPip
  • 53 posts
Hi guys. I have experience in C++ and Java. When writing python programs(presently very simple programs) is there any need for a "main" function as there is in Java or C++?

#2
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,722 posts
  • Programming Language:C, Java, C++, PHP, Python, Perl, Assembly, Bash, Others
  • Learning:JavaScript
Technically no, but in good practice yes. The thing is that a Python script can be used as a library and run as a program itself. Generally what people do is put the following code into Python files they want to be able to execute on their own:

# Put this at the bottom of your file
def main( ...args and stuff in here... ):
    ...do your stuff in here...

if __name__ == "__main__":
    main(...put any arguments in here...)

This way, if someone imports that script as a library instead of executing it directly, that script doesn't try to run as its own program and do weird things.
sudo rm -rf /




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users