SoFunction
Updated on 2024-11-14

The difference between //, / and % in python basics in detail

" // " means to divide by an integer and return an integer, e.g. 7/3 results in 2.

" / " denotes division by a floating-point number, which returns a floating-point number (i.e., a decimal), e.g., 8/2 results in 4.0.

" %" means to take a remainder. For example, 7/4 results in 3.

The sample code is as follows:

It can be run directly in pycharm environment.

a = 321
b = a//100
c = a//10 % 10
d = a % 10

print("The hundredth digit is %d." % b)
print("The tenth digit is %d." % c)
print("The single digit is %d." % d)

The output is as follows.

Expansion:

Using the divmod() function will get both the quotient and remainder The walkthrough code for the IDLE environment is as follows:

>>> divmod(13,3)
(4, 1)

The divmod() function returns a tuple

a = 4321
b = a //1000
c = a //100 %10
d = a //10%10
e = a%10
print("Thousands are",b)
print("Hundreds are",c)
print("The ten digits are",d)
print("Single digit yes.",e)
a = 54321
b = a //10000
c = a //1000 %10
d = a //100%10
e = a//10%10
f = a%10
print("The ten-thousandth digit is",b)
print("Thousands are",c)
print("Hundreds are",d)
print("The ten digits are",e)
print("Single digit yes.",f)

The output result is:

The mantissa is 5.
The thousandth digit is 4.
The hundredth digit is 3.
The tenth digit is 2.
The first digit is 1.

P.S.: A one-minute look at the difference between // and / and % usage in Python

/ (regular except)

As:

5 / 2 = 2.5

Explanation: The usual division is whatever the result is.

// (flooring excepted)

E.g..

5 // 2 = 2 (5 ÷ 2 = 2.5)

5 // 3 = 1 (5 ÷ 3 = 1.6666666666666667)

Explanation: Floor division, removing only the integer portion after the finish.

% (remainder)

As:

5 % 2 = 1 (5 - 2*2 = 1)

4 % 2 = 0 (4 - 2*2 = 0)

7 % 3 = 1 (7 - 3*2 = 1)

13 % 5 = 3 (13 - 5*2 = 3)

Explanation: It is an operation of taking a remainder, dividing by a multiple of the divisor and getting the remainder. The red numbers above indicate the multiples of the divisor.

summarize

To this article on the python foundation of //, / and % difference of the article is introduced to this, more related to the python foundation // / % difference of the content please search for my previous articles or continue to browse the following related articles I hope that you will support me more in the future!