askvity

How do you program floor division in Python?

Published in Python Operators 2 mins read

You perform floor division in Python using the double slash operator //. This operator divides two numbers and rounds the result down to the nearest whole number (integer).

Understanding Floor Division

Floor division is different from regular division (/), which returns a floating-point number. The // operator always returns an integer, even if the operands are floats.

Examples of Floor Division in Python

Here are some examples demonstrating floor division:

# Integer division
result = 15 // 4
print("The floor division of 15 by 4 is:", result)  # Output: 3

# Floor division with negative numbers
print("Floor division of -15 by 4 is:", -15 // 4) # Output: -4

# Floor division using // operator with float values
print("Floor division of 15.0 by 4.0 is:", 15.0 // 4.0) # Output: 3.0

print("Floor division of 15 by 4.0 is:", 15 // 4.0) # Output: 3.0

How Floor Division Works with Negative Numbers

When dealing with negative numbers, floor division always rounds down to the nearest integer, which means moving further away from zero. For example, -15 // 4 results in -4 because -4 is the nearest integer less than or equal to -3.75 (which is the result of -15 / 4).

Key Characteristics of Floor Division:

  • It always returns an integer.
  • It rounds down to the nearest whole number.
  • With negative numbers, it rounds towards negative infinity.
  • It works with both integers and floating-point numbers. If either argument is a float, the result will be a float, but still rounded down to the nearest whole number.

Related Articles