overview edit doc new doc remove

Jan 26, 2018

Python

Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java.

Basics

Comments

# oneline comment

'''
  multi
  line
  comment
'''

Datatypes

varString = 'Sebastiaan'
varInt = 64
varLong = 123548434534L
varFloat = 123.45
varList = [1,2,3,'a','b']
varTuple = (45,56,'b','c')
varDictionary = {'First' : 'first line of the dict' ,
                 'Second' : 'second line of the dict'}
# There is also byte, boolean and byte array

if else

if (<condition>): 

  ...

elif (<condition>):

  ...

else:

  ...

Loops

For

for x in range(0, 10):

  print(x , ' ', end='')

print('\n')

for y in grocery_list:

  print(y)

for x in range(0,50):

  print(x)

While

random_num = random.randrange(0,100)

while (random_num != 15):

  print(random_num)
  random_num = random.randrange(0,100)

Input & output

To read form stdin:

username = input('your name: ')

Collections

varList = [1, 2, 3, 'a', 'b'] # use append / remove
varSet = {1, 2, 3} # use add / remove
varTuple = (45, 56, 'b', 'c')
varDictionary = {'First' : 'first line of the dict' ,
                 'Second' : 'second line of the dict'}

To get the length use: len()

To see the index of a value:

<collection>.index(<value>)

Random numbers

random_num = random.randrange(0,100)

Functions

def <name> (<parameters>):

<tab><code>

Modules

A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.

Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.

import random
import sys
import os

Then call a function from a module by:

<module>.<function>

Error handling

try:

  <code>

# here is an example of a general exception
except Exception as e:
# others: ValueError, ZeroDivisionError

  print(str(e))

finally:

  <code>

NOTE: It is possible to except multiple exceptions.

Basic OOP

Object Orientated programming is a different programming paradigm than the basic procedural programming. Advantages of OO programming are:

Classes

Objects are in fact a custom data type in Python you can define this with a class. The classname starts with a capital letter.

class <Name>:

  <code>

Initialize and object with:

<object> = <className>()

Assign an attribute:

<object>.<attribute> = <something>

Add a method/function to an object with parameters, the new object is passed as argument aswell:

class <Name>

  def <method> (self):

    ...

Constructor

A constructor is used so every time a new object is created a function (constructor) is executed. In this manner you can assign default attributes/behavior for an object.

class <name>:

  def __init__(self):

    <code>

Inheritance

An example of inheritance:

class Shape():

  def __init__ (self):

    self.color = 'Red'

class Square(Shape):

  def __init__ (self, w, c):

    Shape.__init__(self)
    self.width = w
    self.color = c

sq1 = Square(5,'Blue')

Method overriding

It is possible to override a method from the parent object.

New style def

Allows to change the way you call classes in the super class:

class Shape():

  <code>

class Square(Shape)

  def __init__():

    super(Square,self).__init__()

PYQT basics

PYQT ecosystem

PYQT is used for graphical user interfaces. To be able to work with it you will need; SIP and PYQT libraries. PYGTK is another library for building graphical user interfaces bit PYQT is more cross platform compatible.

An example of a PYQT program:

import sys
from PyQt4 import QtGui

app = QtGui.QApplication(sys.argv)

w = QtGui.QWidget()
w.resize(250,120)
w.move(300,300)
w.setWindowTitle('<title>')
w.show()

status = app.exec_()
sys.exit(status)

Events

Events are handled by QApplications.

PYQT widgets

Example of the use of widgets:

import sys
from PyQt4 import QtGui

class MyForm(QtGui.QWidget):

  def __init__(self):

    super(MyForm,self).__init__()

    lbl = QtGui.QLabel('...',self)
    lbl.move(10,20)
    le = QtGui.QtLineEdit('...',self)
    le.move(10,50)

    self.setGeometry(300,300,250,250)
    self.show()

app = QtGui.QApplications(sys.argv)
mainWindow = MyForm()

status = app.exec_()
sys.exit(status)

PYQT advanced

Layouts

Organize widgets into coherent arragements. Simple ways to like up elements in your widget: QVBoxLayout,QHBoxLayout and QGridLayout.

import sys
from PyQt4 import QtGui

class MyForm(QtGui.QWidget):

  def __init__(self):

    super(MyForm, self).__init__()

    lbl1 = QtGui.QLabel('First name')
    lbl2 = QtGui.QLabel('Last name')

    firstname = QtGui.QLineEdit()
    lastname = QtGui.QLineEdit()

    ml = QtGui.QGridLayout()

    ml.addWidget(lbl1, 0, 0)
    ml.addWidget(firstname, 0, 1)

    self.setLayout(ml)
    self.show()

app = QtGui.QApplication(sys.argv)
mainWindow = MyForm()
status = app.exec_()

sys.exit(status)

Handling events

Most events are divided into subevents like a click event is split up in a pressed & released subevent.

An example of a button click event handling:

.
.
btn = QtGui.QPushButton('click me')
btn.pressed.connect(self.handlePressed)
btn.clicked.connect(self.handleClicked)
btn.released.connect(self.handleReleased)
.
.
def handleClicked(self):

  self.lblClicked.setText('Clicked')

.
.

PYPI & PIP

The Python package index is a repository for Python. To install packages from it you can use pip.

sudo pip install <package>

To see installed packages run:

sudo pip list --format=columns

Virtualenv

This tool let you create virtualized isolated environments for Python.

To install:

sudo pip install virtualenv

To create a virtualenv create a directory and use:

virtualenv <directory> <name>

To activate:

source <directory>/<name>/bin/activate

Run deactivate to exit the environment.

Simple HTTP server

To setup a server run:

python -m SimpleHTTPServer

Put an index.html in the directory where you started SimpleHTTPServer and go to localhost:8000/index.html

Web frameworks

There are a lot of different Python web frameworks populars are: Django, Charrypy, WebPy and Flask.

Cherry Py

To install:

pip install cherrypy

Make a cherrypy program:

import cherrypy

class HelloWorld():

  def index(self):

    return 'Hello world'

  index.exposed = True

  def pageX(self):

    return 'Another page'

  pageX.exposed = True

cherrypy.quickstart(HelloWorld())

Unit testing

Create a test class and import unittest.

import unittest

def ExponentCalc(x,y):

  return x**y

class ExponentCalcTest(unittest.TestCase):

  def testSuccess(self):

    result = ExponentCalc(5,4)
    self.assertEqual(result,624)

unittest.main()
1