2
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?

6
  • May be you are missing remaining part of the function in the code above. Commented Mar 13, 2018 at 15:34
  • 1
    What is the initial value of b? Commented Mar 13, 2018 at 15:35
  • what are you returning from? is this inside a function? Commented Mar 13, 2018 at 15:36
  • 1
    If you're using Py3 you cannot garantee that b will be zero at any point of the loop for all possible values of b (remember that Python 3 has true division so 2.5 / 10 is 0.25, not 0.0). Commented Mar 13, 2018 at 15:45
  • 1
    You can only divide by 10 so many times before you get a value so close to zero that b / 10 will be zero itself. Commented Mar 13, 2018 at 16:20

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.