Python Forum
The "in" function, weird output
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
The "in" function, weird output
#1
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"?
Reply
#2
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.
Reply
#3
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...
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
Thanks for the replies.

I'm working on eDx Microsoft Beginner Python course
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Problem with function output slyfox 1 1,471 Nov-27-2019, 07:01 PM
Last Post: jefsummers
  function output student8 1 2,462 Oct-12-2017, 05:30 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020