I don’t see any ‘else’ statement in your example. The way this function runs depends upon the indentation, which we can only guess at. To properly enter code, use the </> icon found in the menu bar at the top of the text box when you are typing. Did you mean this?
if(rating <= 5):
return 'Avoid at all costs!'
elif(5 <= rating < 9):
return 'This one was fun.'
Avoid at all costs!
This one was fun.
I think that you might be asking why else was omitted here. Is that right?
else could be put in, so that the function ended with
… and it would work the same way, but it is unnecessary (as it is in the twice_as_large() example.) The key is the indentation of the final return statement. Remember that return returns a value and then halts the function.
So in the “movies” example,
If the rating is less than or equal to 5, the first if block is entered, function returns ‘Avoid at all costs!’, and then stops.
If the rating is greater than 5, but less than 9, the first if block is bypassed, the elif block is entered, , the function returns ‘This one was fun’, and then stops.
If the rating is greater than 9, both the if and the elif are skipped. Now, at this point, we don’t care what the rating is. We know that it is greater than 9, so no more categories are needed. The only thing left to do is return ‘Outstanding’ and halt the function. That would happen whether return were inside of an else block, or placed at the left-most indentation level within the function, as shown above.
Wondering if my second condition would be correct? if(rating < 9): numbers 1-5 should only return "Avoid at all costs!``` then it would stop reading the code and not return “Avoid at all costs!”. thanks
if(rating <= 5):
return "Avoid at all costs!"
if(rating < 9):
return "This one was fun."
When the action of a conditional branch is to return then it will have already been excluded if the next conditional is reached. Yes, at this point (the second if statement) the value is greater than 5 so your thinking is correct.
Bottom line, return is final. Nothing is reachable after that.