Notes by Keyword

University Engineering

Notes by Category University Engineering

Mechanics & Stress Analysis*
Rate these notesNot a fanNot so goodGoodVery goodBrillRate these notes
  • Engineering Notes

Python Cheat Sheet


Before you can use libraries, you need to import them. For maths:

import maths

For random:

import random

If the library name i slong, such as for plotting, you can set a shortened name:

import matplotlib.pyplot as plot

Useful random functions

To generate a random number, n, in the range 0 ≤ n < 1:

n = random.random()

To generate a random integer, n, in the range a ≤ n ≤ b:

n = random.randint(a,b)

Therefore, a function for rolling a standard six-sided die is:

roll = random.randint(1,6)

Lists / Arrays

n number of data points can be stored in lists, where each data point is given an index address. The first term has address [0], and the last term has address [n-1]. Indexing can be done in negative: in this case, the last term has address [-1] and the first term has address [n].

Defining Lists

To define lists manually:

Age = [18, 18, 19, 18, 17 ... ]
Colour = ['Blue', 'Green', 'Yellow' ...]

Note that you need to put strings in quote marks.

To define lists automatically as a list of integers from a range of a to b:

R = range(a, b+1)
A = []
for members in R:
    A = A + [members]

To generate a list from a series of values, for example a set of random numbers:

for members in A:
    members = random.randint(1,6)