Python Numbers

  • Python

In this article, we’ll learn about number, different types and how mathematical operations are done in Python.

Python has support for integer, float, and complex type numbers and they are defined by int, float and complex. Let’s understand this by examples.

# Integer
a = 2

# Float
b = 4.0

# Complex
c = 1 + 2j

You can check it’s type by using type() function.

print(type(a))
print(type(b))
print(type(c))

Output :

<class 'int'>
<class 'float'>
<class 'complex'>

Type Conversions

We can convert one type into another by using int(), float() and complex() methods.

# Integer
a = 2

# Float
b = 4.0

# Complex
c = 1 + 2j

# convert from int to float
x = float(a)

# convert float to int
y = int(b)

# convert from int to complex
z = complex(a)

print(x)
print(y)
print(z)

print(type(x))
print(type(y))
print(type(z))

Output ;

2.0
4
(2+0j)
<class 'float'>
<class 'int'>
<class 'complex'>

Mathematical Operations

Let’s check out the mathematical operations supported in python

# Addition
print(2 + 2)

# Subtraction
print(13 - 4)

# Multiplication
print(6 * 3)

# Division
print(4 / 2)

# Modulo
print(7 % 2)

After you run the program, the output will be :

4
9
18
2.0
1

In above example, we covered all the basic arithmetic operators. You’re aware with almost most of them. The last one is Modulo which outputs the remainder when 7 is divided by 2.

Here’s another example of Modulo Operation :

>>> 10 % 2
0
>>> 3 % 2
1

When working with numbers, you should remember that Python follows BODMAS rule when computing calculations and most common calculation mistakes are done NOT following this rule.

B rackets
O order
D ivision
M ultiplication
A ddition
S ubtraction

Let’s take an example to understand this better.

3 * 9 - 2

Many of us would be expecting the output as 21 but the actual output is 25 and this is one of the most common mistakes beginners do while learning Python and it’s okay because this is how we learn. If you want 21 as the output, code will be as :

3 * (9 - 2)

And this goes for other operators as well. I hope you were able to run the basic python scripts on your own and everything was clear. Follow the next part of the course.