Floor division operator in python

Summary: in this tutorial, you’ll learn about Python floor division operator [//] or mod.

Introduction to Python floor division

Suppose you have a division of two integers:

101 / 4

In this division, 101 is called a numerator [N] and 4 is called a denominator [D].

The integer division 101 / 4 returns 25 with the remainder 1. In other words:

101 / 4 = 25 with remainder 1

Code language: plaintext [plaintext]

Or put it in another way:

101 = 4 * 25 + 1

Code language: plaintext [plaintext]

Python uses two operators // and % that returns the result of the division:

101 // 4 = 25 101 % 4 = 1

Code language: plaintext [plaintext]

The // is called the floor division operator or div. And the % is called the modulo operator or mod.

This tutorial focuses on the floor division operator. You’ll learn about the modulo operator in the following tutorial.

Both floor division and modulo operators satisfy the following equation:

101 = 4 * [101 // 4] + [101 % 4] 101 = 4 * 25 + 1

Code language: plaintext [plaintext]

Generally, if N is the numerator and D is the denominator, then the floor division and modulo operators always satisfy the following equation:

N = D * [ N // D] + [N % D]

Code language: plaintext [plaintext]

To understand the floor division, you first need to understand the floor of a real number.

The floor of a real number is the largest integer less than or equal to the number. In other words:

floor[r] = n, n is an integr and n

Chủ Đề