sai lohith
sai lohith

Reputation: 21

While statement in python

while b:
    n.append(int(b%10))
    b=b/10
return n

Here the while statement is not stopping even when b=0, what is the problem with this?

Upvotes: 2

Views: 202

Answers (4)

VPfB
VPfB

Reputation: 17237

The most efficient way to compute the reminder and the integer quotient is divmod.

while b:
    b, m = divmod(b, 10)
    n.append(m)

This loop stops for non-negative b.

Upvotes: 1

Paul Brown
Paul Brown

Reputation: 2403

As neither valid answer is accepted, I'll offer the alternative solution, which is to change the stopping condition of the while loop. This lets you keep your floating point division should you need it for some case not in the original question. You can also do the integer division with the shorthand b //= 10.

while int(b):  # Or more explicitly: while bool(int(b)):
    n.append(int(b%10))
    b /= 10
return n

Upvotes: 0

FatihAkici
FatihAkici

Reputation: 5109

Let's simplify your while loop and remove the unnecessary parts:

while b:
    b = b/10
    print(b)

What this does is, it takes a given b, divides it by 10, and assigns this as b. Now the "divide by 10" part is tricky.

  • If you are using Python 2, it works as an integer division:

    19/10 = 1
    

    Let's divide this one more time:

    1/10 = 0
    
  • But in Python 3, this is an actual, proper division:

    19/10 = 1.9
    

    Let's divide this one also one more time:

    1.9/10 = 0.19
    

So in Python 2, your loop will keep rounding the division down, and you will reach 0 eventually. But in Python 3, you will keep dividing your float properly, and will never reach 0. This will mean that your while will never terminate.

Solution: If you want to end up at 0 eventually through integer division so that your loop ends at some point, you can use a//b in Python 3 to get the same behavior of a/b in Python 2.

Upvotes: 1

Susensio
Susensio

Reputation: 860

I think you want to do integer division, if that is the case your code should have // instead of /

while b:
    n.append(int(b%10))
    b=b//10
return n

Upvotes: 0

Related Questions