Search code examples
pythonreturnboolean-operations

Why doesn't functions doesn't return false in python


def sleep_in(weekday, vacation):
    if weekday == ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'] and vacation == 'Yes':
        return True
    elif weekday != ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'] or vacation == 'Yes':
        return True
    else:
        return False


print(sleep_in('monday', 'No'))

Solution

  • Here's some better code:

    def sleep_in(weekday, vacation):
        if vacation:
            return True
        if weekday in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']:
            return False
        else:
            return True
    

    This code works because it first checks vacation, and returns True when vacation is true (you can simply do if vacation for this).

    Next, if vacation is false, it evaluates the next if statement, and sees whether the weekday parameter is within the list of ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']. If it is, it returns False (no sleep_in). If it is not, it means it's a weekend and sleep_in returns true.

    I think that's the goal you were trying to achieve.