Python Basics
Tabs, Spaces, and Loops
Unlike many other programming languages which use brackets to define the contents of a loop, Python uses tabs or spaces. Here is a simple example:
for ii in range(10): print("I'm in the loop") print("I'm outside the loop")
Do not mix tabs and spaces, the code will fail to run. Most programming text editors or IDE's will automatically replace a tab with 4 space.
Data Types
Integers and Floats
The float() method is used to return a floating point number from a number or a string. The int() method returns an integer from a float. If you wan to return an integer from a string, you can call the float method on the string inside the int() method.
>>> x,y = 1,2.6 >>> print(float(x)) 1.0 >>> print(float(y)) 2.6 >>> print(int(x)) 1 >>> print(int(y)) 2 >>> print(int(float('12.4'))) 12
Lists and Tuples
Lists and tuples are very similar. The main difference between the two is that the tuple object does not support item assignment and is immutable. The list is arguably one of the most versatile data types in python. Here is an example showing the similarity and differences of lists and tuples.
>>> a = [1,2,3,'T-Bots',range(5)] b=tuple(a) >>> a+a [3, 2, 3, 'T-Bots', [0, 1, 2, 3, 4], 3, 2, 3, 'T-Bots', [0, 1, 2, 3, 4]] >>> b+b (3, 2, 3, 'T-Bots', [0, 1, 2, 3, 4], 3, 2, 3, 'T-Bots', [0, 1, 2, 3, 4]) >>> a[0]=5 >>> b[0]=5 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment
Dictionaries
A dictionary is a changeable, indexable collection. It has keys and values and is written with curly brackets as follows:
dict = {"Company": "KliK Robotics LTD", "Year of Incorporation": "23 June 2017"} print(dict)
Unlike a list, it is not ordered, meaning the entries might not occur in the order you entered them. You can call the values by using the keys.
>>> dict.keys() ['Company', 'Year of Incorporation'] >>> dict["Company"] 'KliK Robotics LTD'
NumPy Arrays and Matrices
NumPy arrays and matrices are very similar in that they can be indexed in the same way and can be manipulated using mathematical operators. However, there are some subtleties. If we create an array and a matrix with identical elements, we can see the difference in operations.
>>> a = np.array([[1,2,3],[4,5,6],[7,8,9]]) >>> b = np.matrix([[1,2,3],[4,5,6],[7,8,9]]) >>> a*a array([[ 1, 4, 9], [16, 25, 36], [49, 64, 81]]) >>> b*b matrix([[ 30, 36, 42], [ 66, 81, 96], [102, 126, 150]])
For the array, the multiplication is an element-wise multiplication. Whereas matrix multiplication, as might be expected, is done on the matrix. If you want to do this kind of operation on the array, you can use:
>>> np.dot(a,a) array([[ 30, 36, 42], [ 66, 81, 96], [102, 126, 150]])
Likewise, if you want to do an element-wise multiplication of a matrix, you can do:
>>> np.multiply(b,b) matrix([[ 1, 4, 9], [16, 25, 36], [49, 64, 81]])
Classes, methods and functions.
A class is a template for creating an object. Objects may include data and methods. A method is similar to a function but is associated with the object or class.
Functions
Lets start with a simple function. To create a function, def is used followed by the name of the function with the arguments placed in brackets separated by commas. The definition line is closed with a : then the actual function is defined after the tab (or 4 spaces). This example will allow you to create a Gaussian distribution curve. Note this example requires NumPy to be imported first:
import numpy as np def gauss(x,sigma, intensity,centre, bg): return intensity*np.exp(-(((x)-centre)**2.0/(2*sigma**2)))+bg
Now the function can be used as follows:
xdata = np.linspace(0,10,100) ydata = gauss(xdata,2,10,5,2)
Classes
A class can be created as follows (Note this example is to be used to position text in a PyGame window so PyGame must be imported first):
import pygame class TextPrint(object): '''Text positioning class for PyGame''' def __init__(self, textcolour): self.reset() self.textcolour = textcolour self.font = pygame.font.Font(None, 15)
The __init__() method is used to assign values to object properties. The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class. This can be call something other than self if you choose.
Now we can add some other methods:
def tprint(self, screen, textString): textBitmap = self.font.render(textString, True, self.textcolour) screen.blit(textBitmap, (self.x, self.y)) self.y += self.line_height def reset(self): self.x = 10 self.y = 10 self.line_height = 15 def indent(self): self.x += 10 def unindent(self): self.x -= 10 def abspos(self,screen, textString, pos): self.x = pos[0] self.y = pos[1] textBitmap = self.font.render(textString, True, self.textcolour) screen.blit(textBitmap, (self.x, self.y)) self.y += self.line_height def setColour(self, textcolour): self.textcolour = textcolour
It is common to write classes in a separate file and place it in a special folder called a module. Any folder can be made into a module by adding an empty file with the following name: __init__.py If we called our file pgt.py and placed it in a module folder called TbotTools, we would import it as follows:
from TBotTools import pgt
Then we would instantiate it like this:
textPrint = pgt.TextPrint(pygame.Color('white'))
Then it can be used like this:
textPrint.abspos(screen, "Some Data: {}".format(str(SomeValue)),(10,10))