Python as a basic calculator

Aug 21, 2023

DataSciencePursuit

In this section, we will learn how to use Python as a basic calculator to perform basic arithmetic operations. For those who watched the previous video, JupyterLab Tutorial using Python as a Basic Calculator, this page is optional and can be used as a reference. Python can do so much more than basic calculations, but this should be a good start.

Arithmetic operations

For basic calculations, python syntax is the same as most calculators.

Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
** Exponentiation
% Modulus
// Floor

Addition

Subtraction

Multiplication

Division

Modulus (remainder)

Floor (integer division)

Syntax errors

The syntax for arithmetic is number operator number , you will get a syntax error otherwise. Luckily python shows us where the error may have occurred. Here are example code samples that will give you syntax errors.

Semantics and order of operations

For those who have not read the, What is Programming page yet, semantics is what the code means, which is what the computer will do. A semantic error occurs when you give the computer an incorrect command for the task you want to do. Forgetting the order of operations can be an example of a semantic error at this point. Recall BODMAS or BOMDAS or PEMDAS e.t.c. from school. No matter which acronym you learnt, the following is the order of operations:

BODMAS - Brackets (or Paranthesis), Orders (exponents/powers), Division and Multiplication, Addition and Subtraction.

Note: Division and Multiplication are a pair, they have the same order of operations. We start with whichever comes first, from the left to the right. The same applies to multiplication and division.

If you work from the left to the right, you will get 1 + 1 = 2, then 2 + 2 = 4. But 4 is not the answer we will get. If we run the cell, we will get 3. If you were expecting to get a 4, the code below would be the correct code:

To avoid semantic errors, check that your code output matches what you expect. Correct it otherwise.

Next

We will learn how to store data in Python using Variables.