Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test that variable is not equal to multiple things?

Tags:

python

This is the piece of code I have:

choice = ""

while choice != "1" and choice != "2" and choice != "3": 
    choice = raw_input("pick 1, 2 or 3")

    if choice == "1":
        print "1 it is!"

    elif choice == "2":
        print "2 it is!"

    elif choice == "3":
        print "3 it is!"

    else:
        print "You should choose 1, 2 or 3"

While it works, I feel that it's really clumsy, specifically the while clause. What if I have more acceptable choices? Is there a better way to make the clause?

like image 668
M830078h Avatar asked Sep 23 '12 15:09

M830078h


People also ask

How do you check if a variable is not equal to multiple values?

To check if a variable is not equal to multiple values: Use the logical and (&&) operator to chain multiple conditions. In each condition, use the strict inequality operator (! ==) to check that the variable is not equal to the value. If all conditions pass, the variable is not equal to any of the values.

How do you check if a variable is not equal to multiple values Python?

The most direct way to determine if two values are not equal in Python is to use the != operator (Note: There should not be any space between ! and = ). The != operator returns True if the values on both sides of the operator are not equal to each other.

How do you find if a not equal condition in an if statement?

Equality operators: == and != The result type for these operators is bool . The equal-to operator ( == ) returns true if both operands have the same value; otherwise, it returns false . The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .

How do I test multiple variables in Python?

To test multiple variables x , y , z against a value in Python, use the expression value in {x, y, z} . Checking membership in a set has constant runtime complexity. Thus, this is the most efficient way to test multiple variables against a value.


1 Answers

The while bit could be refactored a little to make it a little bit cleaner by checking if the element is within a list of choices like so

while choice not in [1, 2, 3]:

This is checking if the value of choice is not an element in that list

like image 189
Suhail Patel Avatar answered Oct 28 '22 23:10

Suhail Patel