How do I correctly use Or with strings in an if statement
This is a function I wrote. If I enter Wednesday as the day of the week, the program can't get to it to exe开发者_StackOverflow中文版cute the print code. What is the correct syntax for that line of code to make Wednesday work correctly?
def day(dayOfWeek):
if dayOfWeek == ("Monday" or "Wednesday"):
print("Poetry: 6-7:15 in Chem 131")
The expression ("Monday" or "Wednesday")
in your code is always evaluated to "Monday"
. The operator or
is a logical or
that first tries if its first operand evaluates to True
. If yes, it returns the first operand, otherwise it returns the second operand. Since "Monday"
is "trucy", your comparison always compares with "Monday"
.
Use this instead:
if dayOfWeek in ("Monday", "Wednesday"):
print("Poetry: 6-7:15 in Chem 131")
The answer given by Sven will work, and is probably the best method, but just to demonstrate how to properly use or
, you have to do it like this:
if (dayOfWeek == "Monday") or (dayOfWeek == "Wednesday"):
If you want to use ==
if dayOfWeek == "Monday" or dayOfWeek == "Wednesday":
print("Poetry: 6-7:15 in Chem 131")
精彩评论