Python can be used like a calculator to do math. Operations like addition, subtraction, multiplication, and division can be done with Python. In this post, you'll learn how to do math with Python.

## Arithmetic¶

Python can be used as a calculator to make arithmetic calculations.

Try the following commands in a Python REPL or in a Jupyter notebok using the arithmetic operators `+`

, `-`

, `*`

, `/`

:

### Addition¶

Let's try addition first. Let's add 5 and 3 together. Note the `>>>`

prompt is shown to represent the Python REPL, not a character to type.

```
>>> 5 + 3
8
```

### Multiplication¶

What is the total mass if we have 2 batteries, and each battery has a mass of 5 kg? We can use Python to solve this problem. Multiplication in Python is completed using an asterisk `*`

. Note an asterisk is used, not an `x`

.

```
>>> 5 * 2
10
```

### Division¶

The formula for density is below, where $D$ is density, $m$ is mass and $v$ is volume.

$$ D = \frac{m}{v} $$Let's set $m = 5000$ and $v=2500$. Then we can use Python and the division operator `/`

to solve for $D$.

```
>>> 5000 / 2500
2.0
```

### Exponents¶

The length, width, and height of a battery is 3 cm. What is the area of the base of the battery?

To complete this problem, use the double asterisk symbol `**`

to raise a number to a power. Note a double asterisk `**`

is used and not the carrot or circumflex character `^`

.

```
>>> 3 ** 2
9
```

What is the volume of the battery if each the length, width, and height of the battery are all 3 cm?

```
>>> 3 ** 3
27
```

### Using the previous result¶

Find the mass of the two batteries and two cables.

We can use Python to find the mass of the batteries and then use the answer, which Python saves as an underscore _ to use in our next operation. (The underscore `_`

in Python is comparable to the `ans`

variable in MATLAB)

```
>>> 2 * 5
10
>>> _ + 1.5 + 1
12.5
```

### Summary¶

A summary of the arithmetic operations in Python is below:

Operator | Description | Example | Result |
---|---|---|---|

`+` |
addition | `2 + 3` |
`5` |

`-` |
subtraction | `8 - 6` |
`2` |

`-` |
negative number | `-4` |
`-4` |

`*` |
multiplication | `5 * 2` |
`10` |

`/` |
division | `6 / 3` |
`2` |

`**` |
raises a number to a power | `10**2` |
`100` |

`_` |
returns last saved value | `_ + 7` |
`107` |

### Support

Want to learn more about doing math with Python? Check out my book **Problem Solving with Python** on Amazon (Affiliate Link):