We can use the following operators to do calculations in Python: +, -, *, /, //, %, **
- – and + are the usual subtraction and addition operators
- * is the multiplication operator
- / is the familiar division operator
- // is integer division: it does the division and discards the remainder
- ** raises a value to a power
- % is the modulus operator; it effectively does a division and gives you only the remainder
You can use variables that refer to numbers and literal numbers interchangeably when doing calculations. You can also use brackets () to make expressions easier to read.
Examples
If you’re new to programming, it’s best to start by practising simple expressions, gradually building up your skill with doing calculations.
distance_miles = 5
distance_kilometres = distance_miles * 1.6
print("Distance in kilometres: ", distance_kilometres)
print("Square of 16: ", 16**2)
# Text following a '#' is a comment.
# There are 2.54 cm in an inch
# There are 12 inches in a foot
height = 182 # Height in centimetres
cm_per_foot = 2.54 * 12
# Divide height in cm by cm per foot and discard remainder
feet = height // cm_per_foot
# Get remainder after dividing by cm per foot and convert to inches.
inches = (height % cm_per_foot) // 2.54
print(height, "cm is equal to", feet, "feet and", inches, "inches")
Distance in kilometres: 8.0
Square of 16: 256
182 cm is equal to 5.0 feet and 11.0 inches
Leave a Reply