Hi I am trying to ask the user to input a binary number and checking to see if
the input contains 0's and 1's. If not, I want to inform the user that the input was invalid and ask them to retry.

Any help to fix my code would be greatly appreciated.

binary = int(raw_input("Enter a binary number:"))
for i in range(binary):
    if (binary != 0 or binary != 1):
        print "Invalid input"
        binary = int(raw_input("Enter a binary number:"))

Recommended Answers

All 4 Replies

binary = int(raw_input("Enter a binary number:"))
for i in range(binary):
    print "for loop is testing", i, "in range", binary
    if (binary != 0 or binary != 1):
        print binary, "not equal to 0 or 1"
        binary = int(raw_input("Enter a binary number:"))
    else:
       print binary, "equal to 0 or 1"

You could use list comprehension as well

binary = raw_input()
if False in [f == '0' or f == '1' for f in binary]:
	print "Not Binary"
else:
	print "Is Binary"
still_testing = True
while still_testing:
   bin = raw_input("\nEnter a binary number: ")
   if len(bin):
      still_testing = False
   for num in bin:
       if int(num) not in [0, 1]:
           print "Invalid input for", num
           still_testing = True

Not to be too terribly picky, but the code in the above post where it uses if int(num) not in [0,1]: will fail if the user enters non-digit characters.

If the test were performed with strings it would not fail: if num not in ['0','1']:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.