From NoskeWiki
Jump to navigation Jump to search


Python is a highly popular high-level programming language with a focus on code readability and minimal lines of code. Unlike most languages which use braces (C++, Java, etc), python uses indentation to create code block (inside conditional statements and loops).

I've only done a small amount in Python, but I'm hoping to get competency / readability soon. Until then, I'll document useful pieces of code I write here.

Child Pages

Related/Child Pages:

Installing Python

Before you can create a hello world, you must install python. Visit the website to download and install the latest version of python.

Each OS should have an installer... for Windows for example I followed the latest version and used the "Windows x86-64 executable installer" (python-3.5.0-amd64.exe) link.... and by ticking the "add to PATH" option you can then run "cmd" and type "python".

Warning: There are some significant differences between python 2.7 and the new python 3.x.... some of the code below may need adjusting depending which version you downloaded

Creating a Hello World in Python

To execute a python program, install python (instructions above) then create a text file with a .py extension like the following:

print ("Hello, World!")

Now start a new Terminal and run:

$ python

Although this hello world example works fine, a good practice is make the file executable on it's own. Change "" to:

#!/usr/bin/env python
print ("Hello again, World!")

The #!/usr/bin/env python line tells it to add python to the front if directly executed. The following two commands make it executable and then execute it:

$ chmod a+x
$ ./

Python Templates

Python Bare Bones Command Line Program With Arguments

Good practice is to have a "def main()". The following example includes a main, and also demonstrates the 'optparse' for parsing arguments.

#!/usr/bin/env python
# - command line program which inputs a
# name '-f Andrew' and prints a hello message to that name.
import optparse

usage_str = 'Usage: python -name Andrew'

def main():
  p = optparse.OptionParser()
  p.add_option('--name', '-n', default='World')
  options, arguments = p.parse_args()

  contents = usage_str;
  if != 'World':
    contents = 'Hello ' +;

  print contents + '\n'

if __name__ == '__main__':