Do I need an else statement as a default response for my conditional?

Write your in_range function here:

def in_range(num, lower, upper):
if(num >= lower and num <= upper):
return True
return False

Uncomment these function calls to test your in_range function:

print(in_range(10, 10, 10))

should print True

print(in_range(5, 10, 20))

should print False

Why is there no “else” used in this function?

2 Likes

Whenever our if branch contains a return, and there is only a default return otherwise, we don’t need else.

if something:
    return True
return False

Control flow that does not pass the conditional will fall to the last line, which line will execute and send back the default return.

6 Likes

My question is instead,

why if I write

if something:
return True
else:
return False

it doesn’t give any False output? It comes “None” instead of False…

1 Like

Interesting. How am I able to tell if the return is a default?

if something:
    return True
return False

Here,return False is the default, because if none of the operands to any preceding if: or elif: expressions is True, that is the line to which control will ultimately be passed.

1 Like

Following was my response, and it still ran correctly:

def in_range(num, lower, upper):
if num >= lower and num <= upper:
return “True”
else:
return “False”

# Write your in_range function here:
def in_range(num, lower, upper):
  return num >= lower and num <= upper

#Uncomment these function calls to test your in_range function:
print(in_range(10, 10, 10))
# should print True
print(in_range(5, 10, 20))
# should print False

It should return Boolean True/False, not string “True”/“False”