How to divide Integers with the // floor operator
Posted in Python by Dirk - last update: Feb 07, 2024
10 // 3 in Python - integer division explained
In Python, you can divide integers using the division operator (/
). The division operator returns a floating-point result. If you want to perform integer division and obtain only the quotient without the remainder, you can use the floor division operator (//
). With the float division 10/3 = 3.3333333333333335
with the integer division using the floor operator //
it becomes 10//3 = 3
Division operators in Python
In Python, there are two main division operators: the regular division operator (/
) and the floor division operator (//
). A special case is the modulo operator %
.
Regular Division (/):
The regular division operator (/
) performs standard division and returns a floating-point result.
# Regular division (floating point)
result_regular = 10 / 3
print("Regular Division:", result_regular)
Result:
Regular Division: 3.3333333333333335
Note: There is a difference in how the division operator (/
) behaves between Python 2.x and Python 3.x. In Python 2.x the /
operator performs integer division if both operands are integers. If at least one operand is a float, the division is a floating-point division. In Python 3.x the /
operator always performs floating-point division, regardless of the operand types.
Floor Division (//)
The floor division operator (//
) performs integer division, discarding the remainder, and returns the quotient as an integer.
# Integer division (floor division)
result_integer = 10 // 3
print("Integer Division:", result_integer)
Result
Floor division is useful when you only want the whole number part of the division result, discarding any fractional part.
The modulo operator (%)
To get the remainder of an integer division in Python, you can use the modulo operator %
. The modulo operator returns the remainder when one number is divided by another.
result_remainder = 10 % 3
print("Remainder:", result_remainder)
Output:
In this example, 10 % 3 returns 1 because when you divide 10 by 3, the integer result is 3 and the remainder is 1. The modulo operator is useful for extracting the remainder from integer division..
Divmod function
If you want both the quotient (integer division) and the remainder at the same time in Python you can use the divmod()
function. The divmod()
function takes two arguments and returns a tuple containing the quotient and the remainder.
Example:
result_divmod = divmod(10, 3)
print("Quotient and Remainder:", result_divmod)
Result:
Quotient and Remainder: (3, 1)
In this example, divmod(10, 3)
returns a tuple (3, 1)
, where 3 is the quotient (result of integer division) and 1 is the remainder. You can then access each part of the tuple as needed.
Other articles