Return a specific value when a 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 that I still have:

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

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

That way word(10)will return something like "Error".

+4
source share
5 answers

Normal if/elseshould be sufficient.

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'
+5
source

Using the highly epitonic approach of EAFP c try-except.

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

dict 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'}

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')

:

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

Depending on what you want to do with the string, it may not be advisable to return 'Error'instead of just throwing an error. Otherwise, you will need to check if the line looks like a day of the week or is equal 'Error'every time you use this function.

+5
source

Just translate what you want in Python:

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

He must take care of any whole that is not 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 also write getday()in such a compact form:

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

Source: https://habr.com/ru/post/1687792/


All Articles