Python coding bat warmup returning unexpected True

Question:

Was attempting the following problem:

The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we’re on vacation. Return True if we sleep in.

sleep_in(False, False) → True
sleep_in(True, False) → False
sleep_in(False, True) → True

I tried running the following code to test out the solution.

weekday = 0
vacation = 5

def sleep_in(weekday, vacation):
  if not weekday or vacation:
    return True
  else:
    return False

x = sleep_in(0, 6)
print x

I am expecting a result of False. Yet I am getting True! Any ideas what is going on?

Asked By: hikingpanda

||

Answers:

All Python objects have a boolean value; numeric 0 is considered false, every other number is true.

So 0 is false, 6 is true, and not 0 or 6 evaluates to True because not 0 is True:

>>> not 0
True

See Truth Value Testing in the Python documenation:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

[…]

  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.

As such, you don’t need to use an if statement; just return the expression result directly:

def sleep_in(weekday, vacation):
    return not weekday or vacation
Answered By: Martijn Pieters
weekday = 0
vacation = 1

def sleep_in(weekday,vacation):
    weekday = not weekday
    if weekday or vacation: return True
    return False
print (sleep_in(weekday,vacation))

Basically you are looking for not of first value and second value. Defining them first is better I guess. Outputs are correct. Or a one-liner;

x =lambda weekday,vacation: not weekday or vacation
print (x(0,0))
Answered By: sakirecayyok

Your code will not work for several reasons. To begin with, you do not need to define weekday and vacation to any number as they already pass you in those values as either true or false. Furthermore, all you need to do is check if weekday is != True and vacation is false, and if so return True. Else, you will return false. It is as simple as that

    def sleep_in(weekday, vacation):

      if not weekday or vacation:
         return True
      return False

Additionally, it is returning this error because in python 0 is considered to be false and 6 is true, so it thinks you are trying to set them as boolean values which overrides what you were given. Hope this helps!

Answered By: alex.battikha

The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we’re on vacation. Return True if we sleep in.

The bolded statement itself is the HINT.

if not weekday or vacation:
    return True
return False
Answered By: ide3p
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.