Python

From NoskeWiki
Jump to: navigation, search

About

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 python.org 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 program_name.py".


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:

hello_world.py:

print ("Hello, World!")

Now start a new Terminal and run:

$ python hello_world.py

Although this hello world example works fine, a good practice is make the file executable on it's own. Change "hello_world.py" 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 hello_world.py
$ ./hello_world.py


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.

simple_program_with_args.py:

#!/usr/bin/env python
# simple_program_with_args.py - command line program which inputs a
# name '-f Andrew' and prints a hello message to that name.
import optparse
 
usage_str = 'Usage: python simple_program_with_args.py -name Andrew'
 
def main():
  p = optparse.OptionParser()
  p.add_option('--name', '-n', default='World')
  options, arguments = p.parse_args()
 
  contents = usage_str;
  if options.name != 'World':
    contents = 'Hello ' + options.name;
 
  print contents + '\n'
 
if __name__ == '__main__':
  main()

Links