Python Forum

Full Version: The "in" function, weird output
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
menu = ("salad, pasta, sandwich, pizza, drinks")
choice = input("Enter input: ")
   
print(choice in menu)
    
if choice in menu == True:
    print("Available")
else:
    print("Not Available")
Hi there,

If i were to type salad under input, surely, choice == menu, but why did the output returns "Not Available"?
It is a tricky question, but the documentation explains this
Python's documentation Wrote:Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.
It means that without parentheses, choice in menu == True is the same as
(choice in menu) and (menu == True)
which is False.

Normally, one would write
if choice in menu:
    ...
else:
    ...
Don't hesitate to add parentheses in case of a doubt.
also note that menu = ("salad, pasta, sandwich, pizza, drinks") makes menu a string. It's better if it is tuple of strings instead:
menu = ("salad", "pasta", "sandwich", "pizza", "drinks")
by the way, what course/book/tutorial do you follow? There was almost identical thread recently and there was exactly the same thing - same menu, again string, not tuple...
Thanks for the replies.

I'm working on eDx Microsoft Beginner Python course