4

I have been having some trouble recently with creating a program that counts in binary from 1 to the chosen number.

This is my code at the moment:

num6 = 1
binStr = ''
num5 = input('Please enter a number to be counted to:')
while num5 != num6:
    binStr = str(num6 % 2) + binStr
    num6 //= 2

    num6 = num6 + 1

print(binStr)

For example, if I input 5, it needs to go 1, 10, 11, 100, 101. I just can't seem to get the hang of it. Any help will be appreciated, thanks.

Merlin
  • 24,552
  • 41
  • 131
  • 206
R7mone
  • 41
  • 4
  • Your code doesn't really make sense. Try to explain your logic, and you will probably find the problem(s) by yourself doing so... For example what happens if `num5` is `0`?... – Julien Apr 29 '16 at 02:16
  • @mattsap the question you are refering to explicitly asks for inbuilt which is the opposite of what the OP wants. However it is true that some answers in there do give non builtin implementations. But I believe the OP also wants to understand what is wrong with *his* code rather than just photocopying an answer. – Julien Apr 29 '16 at 02:23
  • Also it is not clear what you mean by binary counting. Please add an example of expected result. – Julien Apr 29 '16 at 02:31
  • I think that's what my issue was. If you look carefully, OP is close to converting his string to binary. I don't think he means he wants to count to binary but rather display a int in binary. But, I too, would like clarification. – mattsap Apr 29 '16 at 02:36
  • For example, if I input 5, its needs to go 1, 10, 11, 100, 101. – R7mone Apr 29 '16 at 03:01

1 Answers1

1

The issue is that you're dividing num6 which has nothing to do with the input number. You don't need to keep count of how many times you divide so you can just divide num5 by two and take the remainder. I put your binary_to_string inside of a function and call it for each number to your input value:

num5 = int(input('Please enter a number to be counted to:'))
for i in range(num5 + 1):
    binStr = ""
    decimal_number = i
    while decimal_number > 0:
        binStr = str(decimal_number % 2) + binStr
        decimal_number //= 2
    print(binStr)
mattsap
  • 3,790
  • 1
  • 15
  • 36
  • I'd like to make the note that I think you should use better variable names than num5 and binStr. I would recommend decimal_number and binary_string respectively. I think binStr is too abbreviated to be clear; though, this is just my opinion. – mattsap Apr 29 '16 at 02:37
  • This is better, but its not counting every binary number. For example, if I input 5, its needs to go 1, 10, 11, 100, 101. – R7mone Apr 29 '16 at 02:57
  • I changed my solution. – mattsap Apr 29 '16 at 03:01
  • So I just found out that def counts as a inbuilt function. Would you be able code a version that doesn't use def? – R7mone Apr 29 '16 at 03:25
  • I've modified the solution. – mattsap Apr 29 '16 at 03:31