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:00
In this lesson, we’ll look at best practices using return statements with conditional statements. A Python function can have more than one return statement.
00:10 The first one encountered ends the function execution. Typically, you’ll see this when the function has conditional statements, when the return value depends on the result of some condition.
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.
00:54
We can write a version of this in Python. Python has a built-in function for absolute value called abs(), so we’re calling this my_abs() to distinguish it from the built-in one.
01:06
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.
