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.
- Python Constructs - some constructs in the python language I forget.
- Unix - Python script - print file with color scheme - a little program I wrote which inputs a text file (in this case HTML) and replaces certain tags with ANSI color codes to produce colored output to the terminal.
- Ncurses ui - shows how to build a simple ncurses interface using Python.
- Cinema 4D - Python scripts - a bunch of scripts I wrote for Cinema 4D in Python.
- Example code:
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".
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 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!")
#!/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 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 # 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()