Python code challenges -when should I use else?

hi all - just starting to learn python and am wondering if one of the following solutions is always better than the other or if it’s just a matter of preference? my first thought is the less lines == better, but interested in hearing other thoughts!

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

vs

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

Hi,
In your example, I’d go with the second as well. But, it works because depending on the value of num you only want one or the other code blocks to run.

Say, if you had a function which checked if a number was even. If it was it added one, if not it added 3, then it doubled the result.

def strangeFunc(n):
  if n % 2 == 0:
     n += 1
  else:
     n += 3
  return 2 * n

Not sure where you’d need that function, but hopefully you get the idea. You could have;

def strangeFunc(n):
  if n % 2 == 0:
    n += 1
    return 2 * n
  n += 3
  return 2 * n

but you’re starting to repeat yourself.
Say you wanted to alter the 2 * n later on. Now you need to remember to alter it in two places.

Personally, I try and go for readability first. It’s easier to go back and tighten things up later once you’re fairly confident it’s working as expected.
Have fun

1 Like

Hi there

Consider this if you’re going for shorter code

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

def also_in_range(num, lower, upper):
	return lower <= num <= upper
 	 
 
print(in_range(5, 4, 10))
print(also_in_range(5,4,10))

The first example is very readable and is clear in intention, and gives the same output as the second, although the latter is more concise. Once you’ve gotten comfortable using if and else, the latter might be worth considering since it’s returning the same outcome.

Happy coding! :sunglasses:

I second that, also in a later stage other people who may not be familiar to Python or the Pythonic way of writing still need to be able to read and understand your code. In that case shorter isn’t always better.

1 Like