【问题标题】:Python conditionals and if statementsPython 条件和 if 语句
【发布时间】:2017-09-13 14:22:18
【问题描述】:

我的 if 语句和条件语句的语法有问题。我正在尝试编写一个函数,该函数根据两个参数返回设置闹钟的时间,即今天是哪一天以及该人是否在度假。我的日子被编码为 0 = 星期日,1 = 星期一 ... 6 = 星期六。该函数需要在工作日不休假时返回'7:00',在工作日休假时返回'10:00',在周末不休假时返回'off'。到目前为止,我有以下代码,但是当我用 print(alarm_clock(0, True)) 调用函数时它应该输出 'off' 时给了我 '10:00'。任何帮助表示赞赏。谢谢

def alarm_clock(day, on_vacation):
    """Alarm clock function"""

    if (int(day) < 6 and int(day) != 0) and not on_vacation:
        return('7:00')

    elif (int(day) == 6 or int(day) == 0) and not on_vacation:
        return('10:00')

    elif (int(day) < 6 or int(day) != 0) and on_vacation:
        return('10:00')

    elif (int(day) == 6 or int(day) == 0) and on_vacation:
        return('off')

【问题讨论】:

  • 在第三条 elif 语句中,将 'or' 更改为 'and'

标签: python if-statement conditional


【解决方案1】:

int(day) &lt; 6 or int(day) != 0 对于day 的任何值都将始终为真,因为每个值(包括0)要么小于6,要么不小于6,它也不等于到0。

编写此类事情的更清晰的方法是对范围使用链式比较,或者对不相交的使用元组成员资格:

def alarm_clock(day, on_vacation):
    """Alarm clock function"""
    day = int(day)
    if 0 != day < 6 and not on_vacation:
        return '7:00'

    elif day in (6, 0) and not on_vacation:
        return '10:00'

    elif 0 != day < 6 and on_vacation:
        return '10:00'

    elif day in (6, 0) and on_vacation:
        return 'off'

还提取出常见的int(day) 并删除虚假括号使代码更简洁。

【讨论】:

    【解决方案2】:

    在第三种情况下将 or 更改为 and:

    def alarm_clock(day, on_vacation):
        """Alarm clock function"""
    
        if (int(day) < 6 and int(day) != 0) and not on_vacation:
            return('7:00')
    
        elif (int(day) == 6 or int(day) == 0) and not on_vacation:
            return('10:00')
    
        elif (int(day) < 6 and int(day) != 0) and on_vacation:
            return('10:00')
    
        elif (int(day) == 6 or int(day) == 0) and on_vacation:
            return('off')
    

    【讨论】:

      【解决方案3】:

      在第三个语句中,or 应该是 and。 print(alarm_clock(0, True)) 在第三个语句中被抓住了,因为当天还不到 6 天,即使它也是第 0 天。

      def alarm_clock(day, on_vacation):
         """Alarm clock function"""
      
         if (int(day) < 6 and int(day) != 0) and not on_vacation:
             return('7:00')
      
         elif (int(day) == 6 or int(day) == 0) and not on_vacation:
             return('10:00')
      
         elif (int(day) < 6 and int(day) != 0) and on_vacation:
             return('10:00')
      
         elif (int(day) == 6 or int(day) == 0) and on_vacation:
             return('off')
      

      【讨论】:

        猜你喜欢
        • 2018-02-22
        • 2012-02-04
        • 2022-11-05
        • 1970-01-01
        • 2019-04-29
        • 2013-12-11
        • 1970-01-01
        • 1970-01-01
        • 2023-02-06
        相关资源
        最近更新 更多