DEV Community

Lilian Mwaura
Lilian Mwaura

Posted on

2 2

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!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay