Search code examples
python-3.xconditional-statementsboolean-operations

Boolean operators and Conditions


I'm struggling to get my code running perfectly.

Question:

Write a function should_shutdown(battery_level, time_on) which returns True if the battery level is less than 4.8 except when the time_on is less than 60. If that is not the case, the function returns True only if the battery level is less than 4.7. In all other situations the function returns False.

My code:

def should_shutdown(battery_level,time_on):
    if battery_level and time_on < 60:
        return False
    elif battery_level < 4.8:
        return True
    else:
        return False

It works just fine, except when i test it with the following:

ans = should_shutdown(4.69, 50)
print(ans)

It returns False, but the correct answer should be True.

Other Tests:

  • should_shutdown(5, 10) Expected: False Got: False

  • should_shutdown(4.74, 90) Expected: True Got: True

  • should_shutdown(4.74, 50) Expected: False Got: False

  • should_shutdown(4.7, 50) Expected: False Got: False

- should_shutdown(4.69, 50) Expected: True Got: False

  • should_shutdown(4.75, 60) Expected: True Got: True

  • should_shutdown(4.75, 59) Expected: False Got: False


Solution

  • def should_shutdown(battery_level, time_on):
        if battery_level < 4.8:
            if time_on < 60:
                return False
            else:
                return True
        else:
            if battery_level < 4.7:
                return True
            else:
                return False
    

    Your problem lies in the first if-statement:

    if battery_level and time_on < 60:
    

    This is the same as

    if battery_level!=0 and time_on<60:
    

    This is because in python, any number that is not 0 evaluates to True. Perhaps you meant:

    if battery_level<4.8 and time_on < 60: