Kodeclik Logo

Our Programs

Learn More

Schedule

Kodeclik Blog

Python’s Double Slash

You are likely familiar with the division operator in Python (the forward slash, or “/”). In the below code:

print (5/2)

we get:

2.5

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.

Python Double Slash

print (5//2)

The result is:

2

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:

print (5.0//2.0)

yields

2.0

Here is a simple program to print numbers from 1 to 100.

for i in range(101):
  print(i,end=" ")

The output will be:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 
96 97 98 99 100

Let us now use the integer division operator w.r.t. 3:

for i in range(101):
  print(i//3,end=" ")

The output will be:

0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 8 8 8 9 9 9 10 10 10 
11 11 11 12 12 12 13 13 13 14 14 14 15 15 15 16 16 16 17 17 17 18 18 
18 19 19 19 20 20 20 21 21 21 22 22 22 23 23 23 24 24 24 25 25 25 26 
26 26 27 27 27 28 28 28 29 29 29 30 30 30 31 31 31 32 32 32 33 33

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.

Kodeclik sidebar newsletter

Join our mailing list

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

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.