为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我的 else 语句不运行?

为什么我的 else 语句不运行?

白衣非少年 2022-06-02 16:38:52
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: ")如果输入了无效日期,我希望它打印 else 所说的内容,但它会跳到打印“键入 y 以继续:”
查看完整描述

1 回答

?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

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

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

被翻译为“是day == "monday"真实的,还是"Monday"真实的?” 因为"Monday"它总是真实的(因为它是一个非空字符串),你总是会得到这个if块。您的 ifs 和 elifs 应该看起来更像:

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

缩短它的一种方法是:

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

但是,进行相同检查的更简洁的方法是:

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

这将使您的检查不区分大小写。你的其余elif陈述应该做同样的事情。


查看完整回答
反对 回复 2022-06-02
  • 1 回答
  • 0 关注
  • 194 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号