Python

From NoskeWiki
Jump to navigation Jump to 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 that use braces (C++, Java, etc.), python uses indentation to create code blocks (inside conditional statements and loops).

I've only done a small amount in Python when I started this page, but I aimed for 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 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

Hello World

def hello_world():
  """Function that prints hello world."""
  print ('Hello World')

if __name__ == '__main__':
  hello_world()

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()

Basic File Read/Write

File operations usually look like: f = open("file.txt","w",encoding="utf8") ... where r = read, w = write, a = append.... do one of: read, readlines, readline, write, writelines.... and then don't forget to f.close()... unless you've used with, then you don't need to call close:

simple_file_read_then_write.py:

# Open the file for reading and store its content:
with open("input.txt", "r") as file:
    content = file.read()

# Open the file for writing and update its content:
with open("input.txt", "w", encoding="utf8") as file:
    file.write(content + "\nTHE END")

To read line by line you can also do:

f = open('input.txt', 'r', encoding='ascii')
for line in f:
    print(line, end='')
f.close()


Basic Console Input

Yup, just use input() to prompt input on the console:

simple_input_prompt.py:

print('What is your name?')   # ask for their name
my_name = input()
print('Hi, {}'.format(my_name))


Cheatsheet


Links