Python function prints None

13,982

Functions in python return None unless explicitly instructed to do otherwise.

In your function above, you don't take into account the case in which weekday is True. The interpreter reaches the end of the function without reading a return statement (since the condition predecing yours evaluates to False), and returns None.

Edit:

def sleep_in(weekday, vacation):
    return (not weekday or vacation)

There you go =)

Share:
13,982
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I have the following exercise:

    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.

    Here's what I've done, but the second print function only prints 'None'.

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

    Output:

    True
    None
    True
    
  • SilentGhost
    SilentGhost over 13 years
    you don't need brackets there
  • Admin
    Admin over 13 years
    @SilentGhost: The parens aren't needed, yes, but they arguably add clarity.
  • slezica
    slezica over 13 years
    @delnan I think it's good practice to enclose this kind of comparison logic in parenthesis, even if precedence rules make it unnecessary.