为什么我的else语句不运行? [蟒蛇]

时间:2019-09-22 01:54:01

标签: python

cont = "y"

while cont == "y":
    day = input("Enter today's day: ")

    if day == "monday" or "Monday":
        day = day.upper()
        if day in my_class:
            print ("You have ",my_class[day], " today")

    elif day == "tuesday" or "Tuesday":
        day = day.upper()
        if day in my_class:
            print ("You have ",my_class[day], " today")

    elif day == "wednesday" or "Wednesday":
        day = day.upper()
        if day in my_class:
            print ("You have ",my_class[day], " today")

    elif day == "thursday" or "Thursday":
        day = day.upper()
        if day in my_class:
            print ("You have ",my_class[day], " today")

    elif day == "friday" or "Friday":
        day = day.upper()
        if day in my_class:
            print ("You have ",my_class[day], " today")

    else:
        print ("Enter a valid day")

    cont = input("Type y to continue: ")

如果要输入无效的日期,我希望它打印其他显示的内容,但它会跳过打印“ Type y继续:”

1 个答案:

答案 0 :(得分:1)

问题在于您使用or运算符:

if day == "monday" or "Monday":

Is translated asday == "monday"是真实的,还是"Monday"是真实的?”由于"Monday"始终是真实的(因为它是一个非空字符串),因此您将始终获得此if块。您的if和elif应该看起来像:

if day == "monday" or day == "Monday":

一种缩短它的方法是:

if day in ["monday","Monday"]:

但是,执行此检查的一种更干净的方法是:

if day.lower() == "monday":

这将使您的支票不区分大小写。您的elif其余语句也应如此。