-1

I am trying to make a binary number checker that iterates through an integer but I have a problem

TypeError: 'int' object is not iterable

def sort(binary):
    for char in int(binary):
        if char < 1:
            print("no")
        elif char == 1:
            print("yes")
        else:
            print("ERROR\t ERROR\t NOT A BINARY NUMBER")

def main():
    print("Enter A Binary Number")
    binary = input("")
    sort(binary)

main()

How would I fix this?

Crafter2
  • 9
  • 1
  • 3
  • What specifically are you expecting it to iterate over? The binary representation or each digit as a decimal number? – Axe319 Mar 15 '21 at 14:41
  • An integer is _one_ number. You can't iterate over something that isn't a collection. What do you actually want to do? It would help if you posted example input and output values. Please take the [tour], read [what's on-topic here](/help/on-topic), [ask], and the [question checklist](//meta.stackoverflow.com/q/260648/843953) – Pranav Hosangadi Jun 14 '21 at 18:01

2 Answers2

0

You would have to convert it into a string and then convert back to an integer like this

for char in str(binary):
    char = int(char)
    # And then your code
  • 1
    If you look at OP's example, `binary` is already of type `str` since it comes from `input()`. – Axe319 Mar 15 '21 at 14:54
0

In order to iterate over the digits of the string entered by the user you must not convert the string to an integer beforehand.

Then you also need to compare each digit to the characters '0' and '1' instead of the numbers 0 and 1.

def sort(binary):
    for char in binary:
        if char == '0':
            print("no")
        elif char == '1':
            print("yes")
        else:
            print("ERROR\t ERROR\t NOT A BINARY NUMBER")

If you do not need the digit-by-digit output, a simpler way to check if the string entered by the user is a valid base-2 representation of an integer is to try to explicitly convert it as such. If it wasn't valid, you will get a ValueError exception:

try:
    x = int(binary, 2)
except ValueError:
    print("not a binary number")

See: Convert base-2 binary number string to int

mkrieger1
  • 14,486
  • 4
  • 43
  • 54