0

I want to validate an input to only accept 0s or 1s using a while loop. I would like to use the Boolean "OR," so while the input is not equal to 1 or 0, print an error and insist that the user reinputs the value. If it is, continue with the code so that the user can input the rest of the data.

The following codes works when a 1 is input but does not work for the second condition (in this example 0), no matter what the condition is.

number1=int(input("enter the your number)"))
while number1 !=1 or 0:
    print ("You must enter a BINARY number")
    number1=int(input("enter you first binary digit (from the right)"))

number2=int(input("enter the next (from the right)"))
while number2 !=1 or 0:
  print ("You must enter a BINARY number")
  number2=int(input("enter you second binary digit (from the right)"))

and so on...

1
  • You know the zero is simply a zero you are never testing the value for zero. Commented Mar 4, 2015 at 16:57

3 Answers 3

1

Use this instead for multiple values:

while not number1 in (1, 0):
Sign up to request clarification or add additional context in comments.

Comments

1

The other suggestions will work, but I don't think they address the issue of why what you wrote doesn't work, so I'll try to answer that.

Boolean operators like or and and are meant to go between conditions like number1 != 1 and number != 0, not between non-boolean values like 1 and 0. In English, you can write if number1 is not 1 or 0 people will understand that you mean if number1 is not 1 and number1 is not 0, but it doesn't work that way in pretty much any programming language.

So you could write if number1!=1 and number1!=0 or you could write if not (number1==1 or number1==0). Or, as others have suggested, you could write if number1 not in (0,1), which is shorter and which scales up better.

Comments

0

Code:

number1 = int(raw_input("Enter your number: "))
while number1 not in (0,1):
    print("You must enter a binary number.")
    number1 = int(raw_input("Enter your number: "))

number2 = int(raw_input("Enter your second number: "))
while number2 not in (0,1):
    print("You must enter a binary number")
    number2 = int(raw_input("Enter your second number: "))

print(number1, number2)

Output:

Enter your number: 3

You must enter a binary number.

Enter your number: 1

Enter your second number: 7

You must enter a binary number

Enter your second number: 0

(1, 0)

2 Comments

Recursion is usually suggested against - though it works, it can cause an error after too many inputs
Redundant statements is bad form. Your input statements are redundant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.