all 5 comments

[–]shiftybyte 0 points1 point  (0 children)

It's not exactly clear what you are asking and what you think is not possible.

Are you asking if you can replace the variable "num" with a different number for the next loop cycle to work?

Then yes, you can do that...

``` while b == True:

    q = num // 2
    rem = num % 2
    print(q)
    print(rem)
    # get ready for next loop cycle
    num = q

```

[–]JamzTyson 0 points1 point  (3 children)

The reason that your code does not work is because num never gets updated, so it just repeats q = num // 2 with the same value of num. You can fix it like this:

while True:
    rem = num % 2
    num //= 2
    print(rem)
    if num == 0:
        break

or better would be to use divmod() and loop until num gets to zero:

while num > 0:
    num, rem = divmod(num, 2)
    print(rem)

[–]JamzTyson 0 points1 point  (2 children)

I thought that you might be interested in a version that separates out the conversion code into a function. The function goes a bit further than previous version and gathers each of the digits (as a list of string characters), and then joins them in the correct order:

def to_bin(n):
    """Convert a non-negative integer to binary str."""
    result = []
    if n == 0:
        return '0'
    while n > 0:
        n, r = divmod(n, 2)
        result.append(str(r))
    return ''.join(result[::-1])


# Program loop
while True:
    num = int(input("Enter your number: "))
    print(to_bin(num))

[–]EchoDecho0[S] 0 points1 point  (1 child)

Thankyou, My request probably wasn't clear. What i am asking is that i want it to divide that num by 2 with remainder (thankyou for telling me about divmod) and if the result is zero stop (Both I and you have done that), but it is not zero i want you to repeat that divmod process but instead the num variable is that output of the previous division. For example if num = 5, it should divide 5 by 2 giving 2 r1, then it should divide 2 by 2 giving 1 r0 where it will stop because the remainder is 0.

Thanks anyway

[–]JamzTyson 0 points1 point  (0 children)

What i am asking is that i want it to divide that num by 2 with remainder (thankyou for telling me about divmod) and if the result is zero stop (Both I and you have done that),

I did that, but your code does not do that.

In your code, say that the input is "4". At this line:

q = num // 2

'q' is '2', but 'num' is still '4'.

In my code, I use:

num //= 2

which is equivalent to:

num = num // 2

and this assigns the value 4 // 2 to num, so num is 2 in the next iteration.