-1

Learning Python using a textbook and codecademy.

This code is returning a SyntaxError. Can I not use two greater/less than symbols in the same elif statement? Or is the problem my '<='?

def movie_rating(rating):
    if rating <= 5:
        return "Avoid"
    elif rating > 5 and <= 9:
        return "I recommend!"
    else:
        return "Amazing"
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Scott
  • 5
  • 4
  • 4
    `elif rating > 5 and rating <= 9:` The problem is that `<=` needs something on the left side to compare to. we need to be explicit that we want **`rating`** less than equal to 9. – spencer7593 Jan 15 '19 at 17:36
  • First issue is indentation. Fix that. – dawg Jan 15 '19 at 17:37
  • 5
    `elif 5 < rating <= 9:` – dawg Jan 15 '19 at 17:38
  • @spencer7593 - thank you so much much! Such a simple mistake I completely overlooked. – Scott Jan 15 '19 at 17:42
  • 4
    in this context, we've already done the check of `rating <= 5`, so if we fall into the `elif`, we don't need to confirm that rating is greater than 5. That is, we will get the same result with just **`elif rating <= 9:`** (And this is a better way to do the range check, in case we decide to change our Avoid rating to be less than or equal to 4, we only have to change the 5 to a 4 in one place. (If we don't want a rating of 5 to fall through to 'Amazing'.) – spencer7593 Jan 15 '19 at 17:46
  • Oh, I see! That makes a lot of sense. Thanks for taking the time to explain this to me and giving me a better understanding :) – Scott Jan 15 '19 at 17:52

1 Answers1

0

The problem is because of your and in line 4, this error happening because when you use and you need to define a new condition in other word you should change your code to one of this codes:

def movie_rating(rating):
    if rating <= 5:
        return "Avoid"
    elif rating > 5 and rating <= 9:
        return "I recommend!"
    else:
        return "Amazing"

or change your code to this:

def movie_rating(rating):
    if rating <= 5:
        return "Avoid"
    elif 5> rating <= 9:
        return "I recommend!"
    else:
        return "Amazing"

if you want to know how you can use and in python, follow this link:

How to use boolean 'and' in Python and how use if and else elif or

Ali Akhtari
  • 1,211
  • 2
  • 21
  • 42
  • 2
    oh yes your right, sorry, that was unwanted. now I changed my answer, and its obvious that rating is always bigger smaller than 5 while its smaller than 9, but my point is that syntax is wrong and Im not taking about logic of this code. – Ali Akhtari Jan 15 '19 at 18:22
  • 1
    The `5 <` is not even needed here, since all cases where it is false have already been handled in the `if`. You can just do `if rating <= 5: ... elif rating <= 9: ...` – Blckknght Jan 15 '19 at 18:59