#🔒 Dealing with iterations of a while loop (Very simple ,IT WILL TAKE YOU A MINUTE)

23 messages · Page 1 of 1 (latest)

valid tapir
#

x = 23
while x != 0:
g = x % 2
x = x //2

basically this small program converts a number to binary right . I want to store the value printed out by g every new iterations value of g to some variable . when I try to do some like this : o = g + 1 .it adds 1 to every iteration of the value of one . please and let me know if I need to clarify

civic notchBOT
#

@valid tapir

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

bronze marlin
#

You want to represent binary as a string.

valid tapir
#

not exactly I want to just add the values of binary together basically sum them within a while loop

bronze marlin
#

Otherwise you're just copying the number in a roundabout way

valid tapir
#

yeah it just keep adding the new iteration and not storing the value and constantly updating it

#

I hope im making sense

bronze marlin
#

Try adding each digit to a list instead.

#

g.append(x % 2)

#

or g += x % 2 to skip the sum logic later

#

!e ```py
x = 23
print(bin(x))
g = 0
while x != 0:
g += x % 2
x = x //2
print(g)

civic notchBOT
valid tapir
#

okay let me try that

#

it worked thank you so much

scarlet flare
#

FYI :- @valid tapir if this is not an assignment or a task by university, there is a python built-in function which does exactly this.

bronze marlin
#

f"{x:b}".count("1")

runic agate
civic notchBOT
#

int.bit_count()```
Return the number of ones in the binary representation of the absolute value of the integer. This is also known as the population count. Example:

```py
>>> n = 19
>>> bin(n)
'0b10011'
>>> n.bit_count()
3
>>> (-n).bit_count()
3
```...
bronze marlin
#

Why does this exist?

marsh gyro
#

popcount is a common-ish operation, so it makes sense that it's exposed.

valid tapir
civic notchBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.