Kodeclik Blog

Python’s Double Slash

You are likely familiar with the division operator in Python (the forward slash, or “/”). In the below code:
we get:
as the output. Note that even though both operands to the division operator (in this case, 5 and 2) are integers, the result is a floating point value (2.5).
Let us try the same example but with the double slash.
The result is:
Here, the double slash acts as the integer division operator. It returns the floor of the quotient of its operands, without floating-point rounding. Another way to think of integer division is as an operator that returns just the quotient while discarding the remainder.
You will get the same result even if your original operands were not integers. For instance:
Here is a simple program to print numbers from 1 to 100.
The output will be:
Let us now use the integer division operator w.r.t. 3:
The output will be:
Note the periodicity w,.r.t. 3, the divisor.
Note that this is a Python 3 feature (older versions sometimes indirectly infer whether integer or floating point division is intended based on the types of their arguments). In Python 3, we explicitly declare our preference for integer or floating point division by whether we use double slash (“//”) or single slash (“/”) respectively.
Closely related to the double splash operator, checkout Python's divmod() function!
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2024. All rights reserved.