How to do math in python and working with numbers?


vba Addition, Subtraction, Division, Multiplication, Power, Exp, Modulo remainder.

Numbers in Python works like normal math really. Most of the common transformations that you probably wish to accomplish can be done without calling the specific math module. Should you need more, then rest assure that python's math module has got you covered with all you need.

Below are some examples of your normal math operations

Operation         Sign
Addition          +
Subtraction       -
Multiplication    *
Division          /
Modulus           %    remainder of division. 10 Mod 2 --> 0 (even)
Exponentiation    **   10 ** 2 --> 100. same as 10^2 in math.
Floor division    //   11 // 2 --> 5. rounded down from 5.5  

Common ways to assign values to variables.

All the above operators can in python be used to assign values to a variable in a somewhat quicker way. This is very practical for looping or iterative tasks.


For example instead of writing A = A + 7.

In python, this can be written as A += 7, which is slightly shorter. The "old" way still works but this "new" way is just a slightly shorter and more efficient way of writing it. This statement also works with A -= 7, A *=7, A /=7 or A **= 7 etc..


Comparison operators

Operator  Name                                    Example
==        Equal                                   A == B
!=        Not Equal                               A != B
<         Less than                               A < B
>         Greater than                            A > B
<=        Less than or equal to                   A <= B
>=        Greater than or equal to                A >= B
and       True, if both statements are true.      1 < 3 and 3 > 1
or        True, if one statements is true.        1 < 3 or 3 > 7
not       True, if logical comparison is False.   not(1 > 3)
in        True, if substring is found.            "P" in "Please"
not in    Reverses the above result.              "P" not in "Fix"

Common math syntaxes

Operation            Result
min(7, 21)           7
max(7, 21)           21
abs(-7)              7
pow(10, 2)           100

Python Math library

For more math operation it is practical to import the "math" library to your python script. import the library with the following syntax:

Import math

This gives you access to most operation you will ever use. I will go through the more common ones below but feel free to look into the entire library here: https://docs.python.org/3/library/math.html

Operation            Result
math.sqrt(9)         3
math.ceil(6.5)       7
math.floor(6.5)      6
math.pi              pi --> 3.14
math.exp(1)          e^(1)

Learn more about Python here for all my posts: https://www.pls-fix-thx.com/python

If you have found this article or website helpful. Please show your support by visiting the shop below.


13 views0 comments