简体   繁体   中英

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 execute 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")

Sven给出的答案将起作用,可能是最好的方法,但只是为了演示如何正确使用, or你必须这样做:

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM