If you’d like a refresher on absolute values or would like to learn more about finding them in Python, then check out How to Find an Absolute Value in Python.
Using return Statements With Conditionals
00:24 As an example, let’s consider the absolute value function for mathematics. The absolute value of a real number x is the number itself if that number is zero or positive, and the absolute value is the opposite of that number—you change its sign—if the number is negative. The negative sign in front of the x means just to change its sign. So if x is negative, the negative of that is going to be a positive number.
It reads almost the same way as the mathematics one. This function takes a number as an argument. If that number is greater than or equal to
0, meaning if it’s zero or positive, we return that number.
Otherwise, if the number is less than
0, meaning it’s negative, we return the opposite of that number, and the opposite of a negative number is positive and we will get a non-negative number in each case. Let’s try this out.
We can call this function on a positive number and get the same number back, we can call this function on a negative number and get the positive number back, and we can call this function on
0 and get
Not a thorough test, but it seems to work in all possible cases. A more Pythonic version of this function leaves out the
elif. If the original condition is
False, then the number must be less than
0, so there’s no need for a second test.
If this condition is
False, the number must have been less than
0, we skip the block, come here to what follows the
if statement and its block, and we just get this
return statement to return the opposite of that number.
It’s greater than (
>), not greater than or equal to (
>=). This is a common programming error: not treating the end points of a range of values properly. In this case, we’re not dealing with the
0 case properly.
it works for
-15, but now if I try
0, we get something weird. It didn’t display anything at all. Well, there was no branch in the function to account for
0, and so we ended up getting Python’s default return,
None, which we can see if I actually try to print the result of calling
What happened is there is a third empty branch, which would be right here, in the case that we get to this
elif and this condition is
False. Since that’s the end of the method, Python defaults by putting the
return None there and we get the
None value returned for us.
It’s important to make sure every branch in your function has an appropriate
return statement, otherwise you’ll get results like this. Next, we’ll look at another topic related to conditionals, and that’s when you want a function to return either
Become a Member to join the conversation.