DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   Python (http://www.daniweb.com/forums/forum114.html)
-   -   Ask user for binary number (http://www.daniweb.com/forums/thread158680.html)

pyth0n Nov 20th, 2008 8:27 pm
Ask user for binary number
 
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:"))

woooee Nov 20th, 2008 9:19 pm
Re: Ask user for binary number
 
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"

Paul Thompson Nov 20th, 2008 9:50 pm
Re: Ask user for binary number
 
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"

woooee Nov 21st, 2008 2:50 pm
Re: Ask user for binary number
 
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

Murtan Nov 30th, 2008 1:10 am
Re: Ask user for binary number
 
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']:


All times are GMT -4. The time now is 4:53 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC