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?
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.
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.
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With