Does Python work with chained If's?


#1

Senidng a Letter

Hey guys! I know I should be using the elif way but as a personal preference I tried doing it with chained iffs and the error it gives is IndentationError: unindent does not match any outer indentation level " File "python", line 42
" return "D" "
^
Im guessing python needs elif and cant work with chained iffs?

def get_letter_grade(score):
    if score >= 60:
       if score >= 70: 
            if score >= 80:
                if score >= 90:
                    return "A"
                return "B"
            return "C"
        return "D"
    else: 
        return "F"


#2

it can work with chained ifs, but its need to be done properly


#3

Hi

the problem appears because the lines if score >= 70: and return "D" do not have the same indentations. The line return "D" is one white space too much on the right

Cheers


#4

It should not be in the same indent

if score >=70:
    return

#6

It should be at the same level :

if score >= 90  -> return A
if score >= 80  -> return B is at the same indent as if score >= 90
if score >= 70  -> return C is at the same indent as if score >= 80
if score >= 60  -> return D is at the same indent as if score >= 70

#7

His return D and if score >= 70 are at the same indent


#8

Nope, his line if score >= 70 begins at column 8 and the line return D at column 9. Copy the code in an editor to check

and the error message that he gets is clear on it : IndentationError: unindent does not match any outer indentation level " File "python", line 42
" return "D" "
^


#9

yeah you are right, its one space inside :smiley:


#10

it was not easy to discover this without using an external editor :slight_smile:


#11

I think I get it. Im curious tho how I can avoid that in the future! I tried using tab to change the indentation but it turns out I needed one backspace push. Thank you !!


#12

always use four spaces indention rather than tab


#13

Thank you! :slight_smile: I always thought tab is just easier because you cant mess up the number of spaces and now I know the opposite is possible :slight_smile:


#14

you could also use less spaces 2 for example or just one in case you want to nest that many ifs. Or you could simply use elif:

    def get_letter_grade(score):
        if score >= 90:
             return "A"
        elif score>= 80
             return "B"
        ...