Why does we get the output from the following code as 0.0? | Python Language Forum
H
Heena Goyal Posted on 24/07/2023
x=10
x+=6        # x=6
x-=6        # x=10
x*=6        # x=60
x/=6        # x=10
x%=6        # x=4
print(x)
x//=6
print(x)        #Output goes wrong at this step

Y
Yogesh Chawla Replied on 24/07/2023

x=10
print(f"1-{x}") #10
x+=6
print(f"2-{x}") #16
x-=6
print(f"3-{x}") #10
x*=6
print(f"4-{x}") #60
x/=6
print(f"5-{x}")# 10
x%=6
print(f"6-{x}") #4 - Remainer
x = 10
output=x//6 #this is called as integer divide or floor divide or it gives you quotient
# so if we divide 10 by 6, the quotient is 1 only
# the output was coming 0 because before that statement, the value of x was 4
# and if we divide 4 by 6 and get the quotient, it will be 0 only
# so before that if i change the value to 10, we get output as 1
print(f"7-{output}")   #1


H
Heena Goyal Replied on 26/07/2023

So, when the value of x=4 and we applyx//=6, the quotient will be in decimals i.e. 0.666666...instead of 0. So, what are we missing here about decimals?


Y
Yogesh Chawla Replied on 26/07/2023

#To get the output in decimal, we can also use Decimal class from decimal module

import decimal
print(decimal.Decimal('4') / decimal.Decimal('6'))
x = 4
x /= 6
print(x)
Output is:
0.6666666666666666666666666667
0.6666666666666666

Difference between Floor Divide(//) or Regular Divide(/), Read this:

Floor division is a mathematical operation that is used to divide two numbers and get the result in which the quotient 
is rounded down to the nearest integer value. The floor division operator is denoted by "//" in most programming languages.

For example, if we divide 10 by 3 using floor division, we get:

10 // 3 = 3

Here, the quotient is 3.33, but since we are using floor division, the result is rounded down to the nearest integer, 3. 

In most programming languages, the floor division operator is denoted by "//". It is particularly useful when dealing with 
numbers that need to be truncated or rounded down to obtain a result that is useful for a particular application.



Performing Regular Division in Python

In Python, the regular division operator is denoted by the "/" symbol. It can be used to divide two numbers and get the 
result as a floating-point number.

For example:


x = 20
y = 3
result = x / y
print(result)

Output: 

6.666666666666667

In this example, we are using the regular division operator to divide 20 by 3. 
The result is a floating-point number with several decimal places. The print statement then displays the 
value of 'result' as 6.666666666666667.