Arithmetic Operators
Python is really good at Maths! To do this is makes use of Arithmetic Operators.
Let's take a look at how we can use Python to perform simple calculations
Basic Operators
+ Add
- Subtract
* Multiply
/ Divide
Python can do simple calculations using literal values, for example we could type the following into the Shell:
8 + 5
And the Shell would output the answer.
We could put a longer expression into the Shell, and Python would follow the BODMAS rules when calculating the answer.
e.g.
(6 + 3) * 2 - 3 * 3
Using Variables
We can store the result of an expression in a variable which will allow us to use the answer elsewhere in a program.
Try creating a new program with the following code:
print("I will now add the numbers 8 and 5")
answer = 8 + 5
print("The answer is", answer)
When python looks at the second line of code, it always calculates the result of expression first, then it assigns it to the variable.
When you run the program you should get the following output:
We can also use variables in our expressions.
Try creating a new program with the following code:
num1 = 50
num2 = 20
answer = num1 - num2
print(num1, "take", num2, "equals", answer)
Here the expression in num1 - num2.
Python will fetch the value from num1 (50) and subtract the value from num2 (20), calculate the answer then assign it to the variable answer.
When you run the program you should get the following output:
Think about....
Take a look at the following program:
num1 = 25
num1 = num1 * 2
print("The value in num1 is", num1)
What do you think the output will be?
Why?
Try the program out and see if you were right.
Watch the video about Arithmetic Operators
Key Words
Literal Value
An actual number that is used as given (i.e. not a variable)
Operator
A simple used to describe the type of calculation to be carried out.
Expression
A mathematical calculation that combines numbers (and/or variables) with operators.
BODMAS
The order of operations that is followed when calculating the result of an expression:
Brackets
Orders
Divide and Multiply
Add and Subtract.