DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Lilian Mwaura
Lilian Mwaura

Posted on

Division, Floor Division and Modulus - Python Arithmetic Operators every beginner should know.

What is an Operator?

Operators are used to perform operations on variables and values.
In python, Operators are classified into different categories based on the kind of operations they perform:
They include:

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Identity operators
  • Membership operators
  • Bitwise operators

Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example

  • + Addition x + y
  • - Subtraction x - y
  • * Multiplication x * y
  • / Division x / y
  • % Modulus x % y
  • ** Exponentiation x ** y
  • // Floor division x // y

Difference between Division, Modulus and Floor Division
All these operators are quite interesting because they all perform division, but print different results.

#Division (/) - basically gives out the result of a division.
a = 5
b = 2 
print(5/2)
# result will be 2.5

#Floor Division (//) - Provides the lower-bound of an integral division
a = 5
b = 2
print(5//2)
# result will be 2, the decimal is cut off returning only the whole number

#Modulus(%) - Computes the reminder of a division,which is the 'leftover' of an integral division.
a= 5
b=2
print(5%2)
#result will be 1, which is the 'leftover' integer after the division

Enter fullscreen mode Exit fullscreen mode

First time I learnt all these operations and the different results they print out, I did not quite understand the essence of knowing all these.

But understanding operators comes in handy when solving problems in Python.

For example, modulus is important in finding out even and odd numbers in python.
See the example below :

How to determine even and odd numbers using modulus(%)

n % 2 == 1 
# when n is divided by 2 and the output has a reminder of 1 which means that the number is odd.

n % 2 == 0
# when n is divided by 2 and the is 0, meaning the number is divisible by 2 then the result is an even number.



Enter fullscreen mode Exit fullscreen mode

Hope you learnt something.

Happy Coding!

Top comments (0)

Update Your DEV Experience Level:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. πŸ›