Mathematical Operations in Python
Python natively supports basic mathematical operations, including addition, subtraction, multiplication, division, and exponents. We will investigate those now, and look at additional operators, such as square root, cosine, and factorial in the next lesson.
To begin, Python uses two data types to store numbers, integers and floating point numbers.
- Integer (int) – Integers are positive and negative whole numbers (…-3,-2,-1,0,1,2,3,…).
- Floating point number (float) – floating point numbers are capable of storing positive and negative numbers with fractional values (3.1415, 1.414, 1.0, etc.)
When values are assigned to a variable, Python will select the most appropriate data type based upon the input. It is also possible to change from one data type to another. Floating point values that are converted to integers will have their decimal values truncated. Python will not round the value to the nearest whole number. Here are two examples of changing a data’s type.
diag = 1.414 # By default, Python will store this as a float diag2 = int(diag) # This changes the value to an integer (1) num = 10 # By default, Python will store this as an integer num2 = float(num) # num2 is a float with the value 10.0
Here are the basic operators you should know in Python
- + Addition (eg. 2 + 2) – very straightforward. The sum of two integers is an integer. If one number is a float and the other is an integer, the output will be a float. The sum of two floats is also a float, even if the sum is a whole number.
- – Subtraction (eg. 10.5 – 3) – same rules apply as additional. This symbol is also used to indicate a negative value.
- * Multiplication (eg. 3 * 4) – again, the same rules apply as addition.
- / True Division (eg. 8 / 3) – Python supports two types of division. The first one we will cover is true division, also known as floating point division. Floating point division always returns a float, even when both inputs are integers and the result is a whole number.
- // Floor Division or Integer Division (eg. 5 // 2) – The second type of division Python supports is integer division. In this scenario, the remainder is truncated. You can also think of it as standard division followed by a change of data type from float to integer.
- ** Power (eg. 2 ** 3) – The double asterisk does not indicate integer multiplication. Instead, it raised the number on the left to the value on the right.
- % Modulus (7 % 3) – The modulus operator returns an integer, which is the remainder remainder when dividing the left-hand side of the equation by the right