This notes sheet looks at the fundamentals of python coding: the types of variables, importing and using libraries, basic operations and operators, and using and generating random numbers.
Types of Variables
This is a string of symbols, e.g. numbers and letters. It is noted using single quote marks. If a number is a string, it is not numerical: for example ‘123’ as a string represents ‘1’, ‘2’, ‘3’, and not one-hundred-and-twenty-three.
This is, you guessed it, an integer. These are represented as standard numbers, with no decimal place or quote marks. To convert a string of digits into an integer:
a = '123' int(a) = 123
This is a decimal number, and is represented with a decimal point even if it takes an integer value:
This is when multiple data points are combined. The start and end of the list are marked with square brackets, and the elements in the list are separated with commas. There is no need to add a space, but often it makes things clearer.
The elements can be updated: lists can be written to as well as read from.
[1,2,3,4,5] ['red, 'green', 'blue']
These are like lists, but the elements cannot be updated: tuples are read-only. They are noted using standard parentheses instead of square brackets:
( 1,2,3,4,5 ) ('red', 'green', 'blue')
Lists are represented with square brackets, and can be updated; tuples are represented with standard parentheses and cannot be changed.
Libraries are sets of established mathematical and graphical functions that you can use without having to code them. However, you need to import them. Generally, we import libraries ‘as’ something else: we give them a shortcode, so that we don’t have to write out the whole library name every time we want to call it.
There are two main maths libraries. The former is more basic, whereas the second one allows more complex and concise coding.
import math as maths import numpy as np
Here, we have renamed math as maths, because the Americans are wrong. Meanwhile, numpy has become np – this is a standard shorthand, that basically everyone uses.
The next most important library is matplotlib, which allows us to plot graphs:
import matplotlib.pyplot as plot
The fourth and final library you’ll need every now and then for basic programming is the random one. This can generate random numbers, which is fun:
import random as rn
The print command is used to export a text or number output. To print a variable, simply put the name of the variable in the brackets. To print text and a variable, use single quote marks for the text (it is a string), followed by a comma and then the variable.
print('Hello') print('The answer is: ', A) #where A is a pre defined variable
To print a line break, add /n in quote marks:
A = 99 print('The answer is: \n', A)
These are used if certain conditions must be met in order for a script to be performed:
if x == a: print('x is the same as a') else: print('x and a are not equal')
These are perhaps the most common loops used, as they are used to repeat an action for every element in a range.
The example code below takes the list of integers from 1 to five and multiplies each element by 2. It does this by establishing a dummy variable, i, that initially takes the value 0, then 1, then 2 all the way up to 4.
a = [1,2,3,4,5] for i in range(0,len(a)): a[i] = 2*a[i] print(a)
Inline & Comprehension
This is a method of putting if and for loops in a single line, instead of writing out the full form above. It is not only neater and more compact to write, it is also more efficient for a computer to run.
The if loop above can be comprehended as such:
print('x is the same as a') if x==a else print('x and a are not equal')
While the for loop to double each member in list a can be comprehended too:
a = [1,2,3,4,5] a2 = [i*2 for i in a]
If we want to perform a series of actions over and over again, it is easier to establish these in a function. Then we can simply call this function instead of writing out the code every time.
For example, a function that that returns the hypotenuse of the two perpendicular sides of a right angle triangle:
def Hyp(a,b): h = (a**2 + b**2)**0.5 return h
- the function must be defined using def
- the input variables must be defined in brackets after the function name (in the above case, the function name is Hyp and the inputs are a and b
- The function must end with the return command
- to call the function, simply write the function name (case sensitive) and the input variables in brackets:
print(Hyp(3,4)) #prints 5, because 2,4,5 is a Pythagorean triple
These are similar to functions, but are anonymous. This means they have no assigned name, and can be treated similar to a variable.
h = lambda a,b: (a**2 + b**2)**0.5 print(h(3,4))
The if-else function is used to test Boolean outcomes (where the outcome is either ‘yes’ or ‘no’).
- a == b a equals b
- a != b a does not equal b
- a < b a is less than b
- a > b a is greater than b
- a <= b a is smaller than or equal to b
- a => b a is greater than or equal to b
A nice example is rolling two dice. This requires two loops, the first tests for a draw, the second for a winner.
import random as rn #Setting up rolling functions Die1 = rn.randint(1,6) Die2 = rn.randint(1,6) #Rolling the dice print('Die 1 lands on a', Die1) print('Die 2 lands on a', Die2) if Die1 == Die2: #it is a draw print('It is a draw.') else: if Die1 < Die2: #Die2 wins print('Die 2 wins.') else: #Die1 wins print('Die 1 wins.')
To generate a random float between zero and 1:
To generate a random float in the range [a:b]:
If you want a random integer in the same range: