Ask coding questions

← Back to all posts
##### How do I do this

Im doing an if statement where if a users grade on a test is between two percentages it is a certain grade like if a user gets 91 percent it's an A minus, and so I was coding and I got a problem where I tried to do...

elif percentage >= 90 and <95:
letter_grade = "A-"

I think it is because of the and statement but I don't know how to solve this I need some help

Answered by RYANTADIPARTHI (6009) [earned 5 cycles]
View Answer
##### Comments
hotnewtop
RYANTADIPARTHI (6009)

# Solution

try this

``````letter_grade = None
percentage = 0

if percentage >= 90 and percentage < 95:
letter_grade = "A-"
elif percentage >= 80 and <85:
letter_grade = "B-"
else:
percentage = "C-"``````

and so on.
That should work

JavaTime (1)

There is a better way to do this. For the sake of example I am going to say the following:

A = 100 - 91
B = 90 - 81
C = 80 - 71 etc.

The way I would code this is like this:

if grade >= 91:
letter_grade = A
elif grade >= 81:
letter_grade = B
elif grade >= 71:
letter_grade = C

or you could do it the other way around, starting from the bottom, such as:

if grade <= 80:
letter_grade = C
elif grade <= 90:
letter_grade = B
elif grade <= 100:
letter_grade = A

Tell me if this helps.

Kavin1983 (1)

@JavaTime This is actually very helpful because I forgot that python will only go to the next elif statement if the statement is false. Thanks alot

Kavin1983 (1)

thanks I appreciate all the help

Coder100 (17102)

Yes, you must use two comparisons, like this:

``````if ...:
...
elif percentage >= 90 and percentage < 95:
...``````

just like that, very easy.

IntellectualGuy (714)

Here, the problem is that it's elif not if

``````percentage = 93
letter_grade = ""

if percentange >= 90 and percantage < 95:
letter_grade = "A-"``````
figglediggle (137)

The reason you are getting the error is because the compiler doesn't know what you are comparing 95 to. The proper code would be

``````percentage = 91
letter_grade = ''

if percentage >= 90 and percentage <= 95:
letter_grade = 'A'``````