Is there another way to check for interval?

so awesome thing when testing ranges that i found,

if 5 <= rating < 9:
    return "This one was fun."

Was over here at stackoverflow

Handy when all we want to check is one interval. If there are multiple intervals then it would overkill when simple comparisons will do the job.

You hit on ‘range’, and that’s where an inequality expression is handy.

def double_at_index_if(array, index):
    n = len(array)
    if -n <= index < n:
        array.insert(index, array.pop(index) * 2)
    return array

Above may look similar to an exercise we did a while back, only switched it for a bit of fun. The array will be manipulated at any valid index.

It gets real fun when we introduce exception handling.

def double_at_index_try(array, index):
        array.insert(index, array.pop(index) * 2)
        return array
    except (IndexError, ValueError, TypeError):
        return array
print (double_at_index_if([2, 5, 7, 9], 2))
print (double_at_index_try([2, 5, 7, 9], 2))
print (double_at_index_if([2, 5, 7, 9], -5))
print (double_at_index_try([2, 5, 7, 9], 4))
[2, 5, 14, 9]
[2, 5, 14, 9]
[2, 5, 7, 9]
[2, 5, 7, 9]

When working with booleans and if/else statements I usually skip the ifs and do comparisons directly with the truth values, for example

def movie_review(rating):
  s1="Avoid at all costs!"
  s2="This one was fun."
  return s1*(rating<=5) + s2*(5<rating<9) + s3*(rating>=9)

also in another excercise they asked for a grade according to a gpa value. You could skip the nested ifs and do something like this

def grader(gpa):
  return grade[int(gpa//1)]
1 Like