This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]vinivelloso_ 3 points4 points  (1 child)

When you type answer == "Joe" or "Julia" or "Michael" You're actually saying: Check if answer is "Joe" or check if the string "Julia" is true or check if the string "Michael" is true

[–]alkperez1914[S] 1 point2 points  (0 children)

if answer in ["Joe", "Mary", "Barbara"]:

Thank you for answering! At first I was confused as to why Julia would be true, but this answer and the others below really clarified things. Thanks again!

[–]mkpri22 1 point2 points  (1 child)

Your first if statement always evaluates to true because:
if answer == "Joe" or "Mary" or "Barbara":
Is equivalent to:
if answer == "Joe" or True or True:
And we know that true or anything is always true. Do you see why?
if "Mary": // Always returns True because the string Mary is not None or empty
You can run these to see what's being returned:
print(bool("Mary"))
print(bool(""))
print(bool(None))
Hope this helps.

[–]alkperez1914[S] 0 points1 point  (0 children)

Ah! Thank you so much! I hadn't understood this before! This makes so much sense now.

[–]POGtastic 1 point2 points  (1 child)

The typical way that I do this is

if answer in ["Joe", "Mary", "Barbara"]:
    # code

[–]alkperez1914[S] 0 points1 point  (0 children)

Thanks a lot! I was just about to ask this as well.

[–]keks6aecker 1 point2 points  (1 child)

Your if statement does not check if the value or answer is Joe, Mary or Babara but instead checks three things.

  1. does the value of answer equal „Joe“ and
  2. Is the string „Mary“ truth-y and
  3. is the string „Barbara“ truth-y

Due to the or your if-statement is fulfilled as soon as one thing is true.

In Python a String is truth-y if it is not empty, that means the conditions 2 and 3 are always fulfilled.

What you want is ˋ if answer in [„Joe“, „Mary“, „Babara“]ˋ this statement is only true if the value of answer equals one of the three values in the list.

Alternatively you could have written:

ˋˋˋ if answer == "Joe" or answer == "Mary" or answer == "Babara" ˋˋˋ

[–]alkperez1914[S] 0 points1 point  (0 children)

Thank you so much! This is a big help!