Programming & Scripting Tutorials

Python: Simple Math



In this lesson you will learn about simple math in Python.

Basic math


Firstly open IDLE (Python GUI).
Basic math is really simple in python. Try typing in these simple calculations and see what Python outputs:

7+3
9-8
10/5
5*5

But what about "10/4"?
This outputs 2. The problem is that 10/4 is actually 2.5.
Python looks at the calculation and sees that we are dividing two integers (whole numbers); for this reason it outputs an integer instead of a decimal number.
To make it so that it outputs a decimal number (or a float as they are called) we simply have to add a decimal point to one or both of the numbers. For example:

10.0/4.0


We can also use the modulus operator to find the "remainder".
For example 8/3 in Python would output 2 (as 3 goes into 8, 2 and a bit times).
If we want to know the remainer (in this case 2 (as 3*2 is only 6, we have 2 left over)) we can use the % sign:

8%3


The last simple math calculation we will do in Python is doing something "to the power of" something (called an exponentiation).
We do this in python using a double asterisk - for example "5*5" could also be done using "5**2"(5 to the power of 2).


This Python tutorial was written by


Back to Python

Advertisement: