Back to: Python Programming
Like all programming languages, maths plays a significant part. Today we explore maths operators and functions that use maths in our code.
Addition / Subtraction Operator
Incrementing a variable by 1 (increase by 1)
cycles = 0
cycles = cycles + 1
print(cycles)
We can shorten this code using an “augmented assignment operator”.
cycles = 0
cycles += 1
print(cycles)
Similarly, we can decrement a variable (decrease) by 1
cycles = 10
cycles -= 1
print(cycles)
Multiplication / Division Operator
Increasing by 3 times
cycles = 4
#cycles = cycles * 3
cycles *= 3
print(cycles)
Finally dividing by 2;
cycles = 16
#cycles = cycles / 2
cycles /= 2
print(cycles)
Exponents
The power of 2
cycles = 5
#cycles = cycles ** 2
cycles **= 2
print(cycles)
Modulus
Modulus gives you the remainder of any division – often used to find out if a number is even or odd. Modulus 2 will always be zero for an even number and 1 for odd.
cycles = 11
remainder = cycles % 3
print(remainder)
Functions
Include round, absolute, power, max and min. (try each by removing the comment in front of the function)
x = 3.51
y = -4
z = 7
#result = round(x) # <-- rounds x to nearest integer (4)
#result = abs(y) # <-- distance of the number from zero as a whole (4)
#result = pow(8, 2) # <-- sets result to 8^2 (64)
#result = max(x, y, z) # <-- sets result to largest var. (7)
result = min(x, y, z) # <-- sets result to smallest var. (-4)
print(result)
Classes – The Maths Class
We can import the ‘math’ module to obtain some very useful constants and functions.
For instance, if we need to use the value of π
import math
print(math.pi) # <-- outputs the value of pi
Other mathematical operations include:
import math
x = 9.6
# -- find the square root of x
#result = math.sqrt(x)
# -- round value of x up to the ceiling, 9.6 -> 10
#result = math.ceil(x)
# <-- rounds value of x down to the floor, 9.6 -> 9
result = math.floor(x)
print(result)
Finding the circumference of a circle uses formula Circumference = 2 x π x Radius.
import math
radius = float(input("Enter the radius of the circle: "))
circumference = 2 * math.pi * radius
#print(f"The circumference of the circle is {circumference}")
# -- to round off to three decimal places
print(f"The circumference of the circle is {round(circumference, 3)}")
Exercise 1
Write code to calculate the area of a circle – ask the user for the radius of the circle.
(Area = π x r2) – ensure the result is given to 2 decimal places.
Exercise 2
Find the length of the hypotenuse of a right angled triangle after asking your user to provide the length of side a and side b. (round the answer to 2 decimal places.)
hint: c = √(a2 + b2)