5

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".

1
  • 1
    Where is num coming from? If it's a bad input, it might be a good idea to throw an exception. Commented Oct 19, 2017 at 12:11

5 Answers 5

5

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'
Sign up to request clarification or add additional context in comments.

2 Comments

Every call is complicated to read and maybe he need this call a few times so a own method with own behavoiur is much better. But it´s working -- you´re right.
return l[num-1] if len(l) >= num > 0 else "Error"
5

Using the highly pythonic EAFP approach with a try-except.

daysofweek = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
def getday(num):
    try:
        return daysofweek[num - 1]
    except IndexError:
        return "Error"

2 Comments

It won't not work for negative values or 0. Will go back to last.
@KaushikNP the understanding is OP enters a value between 1 and 8. I’m just showing them how to use the eafp approach, I’m not nitpicking on their function or what it does.
5

You could convert your list to a dict with enumerate(sequence, start=1):

dict(enumerate(['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'], 1))
# {1: 'Sunday', 2: 'Monday', 3: 'Tuesday', 4: 'Wednesday', 5: 'Thursday', 6: 'Friday', 7: 'Saturday'}

Then, your query is a easy as dict.get():

wdays = {1: 'Sunday', 2: 'Monday', 3: 'Tuesday', 4: 'Wednesday', 5: 'Thursday', 6: 'Friday', 7: 'Saturday'}

def word(num):
    return wdays.get(num, 'Error')

Here's an example:

>>> word(3)
'Tuesday'
>>> word(10)
'Error'
>>> word('garbage')
'Error'

Depending on what you want to do with the string, it might not be a good idea to return 'Error' instead of simply throwing an Error. Otherwise, you'll have to check if the string looks like a week-day or is equal to 'Error' every time you use this function.

3 Comments

Another benefit of this approach is that it will also return 'Error' if word is passed any bad arg, not just out-of-range integers.
@PM2Ring: True. But it depends what the goal is. It's often preferrable to throw an exception as soon as bad input is used instead of trying to keep on working with broken data. If I liked this behaviour, I'd write Javascript instead of Python ;)
Indeed. It would be better design to raise ValueError on bad args rather than returning 'Error'. OTOH, string tests are cheaper than exception handling.
2

Simply translating what you want to Python:

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

Comments

0

It should take care of any integer which isn't within your desired range.

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

num_index = int(input("Enter a value for num : "))
print(getday(num_index, len(daysofweek)))

You can write the getday() in a compact form like this as well:

def getday(num, len_range):
    return daysofweek[num - 1] if 0 < num <= len_range else "Error"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.