John Shepley
John Shepley

Reputation: 1

Validating an input using a simple while loop

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...

Upvotes: 0

Views: 14355

Answers (3)

Erik Wennstrom
Erik Wennstrom

Reputation: 134

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.

Upvotes: 1

Stian OK
Stian OK

Reputation: 666

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)

Upvotes: 0

Malik Brahimi
Malik Brahimi

Reputation: 16711

Use this instead for multiple values:

while not number1 in (1, 0):

Upvotes: 1

Related Questions