Search code examples
pythonarraylistreturnrangedefault

Return specific value when list is out of range in Python


How can I return a specific value if the list is out of range? This is the code I have so far:

def word(num):
  return ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][num-1]

word(1) will return 'Sunday', but how can I return a default value if num is not an integer between 1-7?

Thus, word(10) would return something like "Error".


Solution

  • Normal if/else should suffice.

    def word(num):
        l = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
        return l[num-1] if 0<num<=len(l) else "Error"
    

    #driver code

    >>> word(7)
    => 'Saturday'
    
    >>> word(8)
    => 'Error'
    
    >>> word(-10)
    => 'Error'