2017-09-13 187 views
0

我在if語句和條件語句時遇到了問題。我正在嘗試編寫一個函數,該函數返回設置鬧鐘的時間,具體取決於兩個參數,它是哪一天以及該人是否在度假。我的日子編碼爲0 =星期日,1 =星期一...... 6 =星期六。該功能需要返回'7:00'平日而不是休假,'10:00'平日假期和週末不休假,最後在週末不返還假期返回'off'。到目前爲止,我有下面的代碼,但它給我'10:00'當我調用print(alarm_clock(0, True))函數時,它應該輸出'off'而不是。任何幫助讚賞。由於Python條件語句和if語句

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') 
+2

在第3條elif語句中,將'或'更改爲'和' –

回答

0

變化orand在第3條件:

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') 
0

在第三個說法,或者應該是和。 print(alarm_clock(0, True))漸漸在第三語句捕捉到,因爲這一天是不到半年,即使它是也爲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') 
1

int(day) < 6 or int(day) != 0永遠是對的day任何值爲true,因爲每個值(包括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)和消除雜散括號使代碼更清潔一點。