Advanced Python Code Challenges: Control Flow Challenge 4

I wrote my code a little differently and got the same results and am wondering why the solution is written the way it is. It just seems like a really strange way to write it out

The challenge is:
Create a function named movie_review() that has one parameter named rating .

If rating is less than or equal to 5 , return "Avoid at all costs!" . If rating is between 5 and 9 , return "This one was fun." . If rating is 9 or above, return "Outstanding!"

The solution was written as:

def movie_review(rating):
if(rating <= 5):
return “Avoid at all costs!”
if(rating < 9):
return “This one was fun.”
return “Outstanding!”

my code was as follows

def movie_review(rating):
if rating >= 9:
return “Outstanding”
elif rating >= 5:
return “This one was fun”
return “Avoid at all costs!”

Welcome to the forums!

Using an else clause here is completely valid and will accomplish the same thing as the solution code. Here’s a simpler and similar example; I’ll go step-by-step.

def f():
  if 2 > 3:
    return "2 is greater than 3"
  return "2 is not greater than 3"
  1. We start with if 2 > 3. This evaluates to False, meaning the code inside the if block is not executed.
  2. We then move on to the next line outside of the if block, which is return "2 is not greater than 3".

Therefore, when we call f(), "2 is not greater than 3" is returned.

In this way, you can see that the single if statement is enough, since, if the boolean condition evaluates to True, the code inside the if block will be executed. And since the code inside contains a return statement, we will immediately exit the function after the return statement is executed and return "2 is not greater than 3" is not executed.

Similarly, if the if condition evaluates to False, the code inside the if block will not be executed and we go to the next line, which is a return statement, meaning the function will be exited after the execution of the return statement.

Side note: parentheses aren’t necessary in these expressions unless they have an effect on the order of operations/precedence or they make your code more readable.