In Python,//
yesInteger division operator (floor division), it is used to executeDownward rounding division(i.e., remove the decimal part).
1. Basic usage of //
//
The operator will returnThe integer part of the quotient, without rounding. For example:
print(10 // 3) # Output 3print(10 // 4) # Output 2print(-10 // 3) # Output -4 (Round down)
-
10 / 3 = 3.3333...
,and10 // 3
Take only the integer part3。 -
-10 / 3 = -3.3333...
,and-10 // 3
Round downwards and becomes-4(Note the negative number).
2. // vs / (normal division)
Operators | effect | Example | result |
---|---|---|---|
/ |
Normal division (return to floating point number) | 10 / 3 |
3.3333... |
// |
Integer division (rounded down) | 10 // 3 |
3 |
// |
Integer division (rounded down) | -10 // 3 |
-4 |
Example:
print(10 / 3) # 3.3333... print(10 // 3) # 3 print(-10 / 3) # -3.3333... print(-10 // 3) # -4 (Round down)
3. // Function in mid = len(lists) // 2 code
existDividing and treating methodsIn the array, theTwo halves,mid
Calculation method:
mid = len(lists) // 2
Example
lists = [1, 2, 3, 4, 5] mid = len(lists) // 2 # mid = 5 // 2 = 2 print(mid) # Output 2left = lists[:mid] # [1, 2] right = lists[mid:] # [3, 4, 5] print(left, right)
-
len(lists) // 2
calculateMidpoint index of array。 -
lists[:mid]
PickLeft half。 -
lists[mid:]
PickRight half。
4. Handle Parity
Python's//
There will be no index errors due to odd lengths, it always rounds downward:
lists1 = [1, 2, 3, 4, 5] # The length is odd 5lists2 = [1, 2, 3, 4] # length is even 4mid1 = len(lists1) // 2 # 5 // 2 = 2 mid2 = len(lists2) // 2 # 4 // 2 = 2 print(lists1[:mid1], lists1[mid1:]) # [1, 2] and [3, 4, 5]print(lists2[:mid2], lists2[mid2:]) # [1, 2] and [3, 4]
5. // The role in negative number calculation
For negative numbers,//
meetingRound down:
print(-7 // 3) # -3 (because -7 / 3 = -2.3333, round down to -3)print(-7 / 3) # -2.3333...
Note: It is not simply removing the decimal part, but rounding it downwards!
Summarize
-
//
yesInteger division,returnRound downThe result of the , no decimal part is produced. - When calculating indexes (e.g.
mid = len(lists) // 2
) can ensureNo errors, even if the length is odd. - negative number
//
Will stillRound down(For example-7 // 3 == -3
)。 - and
/
different,//
No floating point number is returned。
Applicable to:
✅ Dividing and consolidation algorithm
✅ Index calculation
✅ Integer operation
✅ Avoid floating point errors 🚀
This is the end of this article about dividing operations (rounding down) in python. For more related python dividing down rounding content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!