Last time we reviewed the string and numerous handy methods to manipulate and format strings.
Today we will explore the numeric type and a few methods to work with them.
Data type: Numeric
Python has three numeric data types:
Integer, like other programming languages, is a whole number, positive or negative without decimals.
A float is simply a number, positive or negative, that contains a decimal
Complex numbers are a mathematical way to express numbers with two parts: a real part, and imaginary parts. Complex numbers allow you to solve advanced mathematics problems.
Without going into details, I invite you to search more about complex numbers on the net.
Just know that with Python, the imaginary part is expressed with
j (and not
i like my Maths teacher taught me 👨🏫).
Let's explore some fundamentals methods you may want to use with numeric.
Basic Math Operators
|**||exponent||3 ** 3 = 9|
|%||modulus/remainder||10 % 3 = 1|
|//||integer division||10 % 3 = 3|
|/||division||10 % 3 = 3.3333-|
|*||multiplication||3 * 3 = 9|
|-||subtraction||10 - 3 = 7|
|+||addition||10 + 3 = 13|
These are classed by highest to lowest order or precedence
2 + 3 * 3 ** 2 is equivalent to
2 + ( 3 * (3 ** 2) ) = 29 (if my calculations are correct! 😄).
☝️ Note that when doing division you might convert an
int into a
float, for example:
x = 5 y = 2 print(type(x/y) is float) # >> True (we started with two `int` and ended up with float!)
Advanced Math Operators
For any advanced math operations, Python has a built
math module that contains a long list of advanced math operators, such as
math.acos() for the arc cosine of a number.
It also contains some universal constants, such as
You can find the list of operators here.
Python also comes with assignment operators that allow you to assign and perform a math operation at the same time.
|Operator||Example||Same as||Result if x = 3|
|=||x = 3||x = 3||x = 3|
|+=||x += 3||x = x + 3||x = 6|
|-=||x -= 3||x = x - 3||x = 0|
|*=||x *= 3||x = x * 3||x = 9|
|/=||x /= 3||x = x / 3||x = 1|
|%=||x %= 3||x = x % 3||x = 0|
|**=||x **= 3||x = x ** 3||x = 27|
|>=||greater than or equal to|
|<=||less than or equal to|
The last thing I want us to cover is how we do type conversion.
That is if I have an integer, or do I convert it to a float?
It's pretty simple, we use
You can also use
str to convert them to string!
i = 3 f = 3.9 print(int(f)) # >> 3 (the decimal part is dropped) print(float(i)) # >> 3.0 print(str(int(f))) # >> "3"
That's it for the numeric data type in Python!
These few methods should give you a lot to work with.
See you next time 👋