re: The `else if` Keyword Doesn’t Exist in Java VIEW POST

FULL DISCUSSION
 

Maybe this counts as mind blowing as well. The elif if python does not work any differently than the else if in Java. The only valid reason for having this elif construct is the formatting. In Python you would have to use correct spacing when using else if

if grade >= 90:
  print("You got an A!")
else:
  if grade >= 80:
    print("You got a B!")
  else: 
    if grade >= 70:
      print("You got a C!")
    else:
      if grade >= 60:
        print("You got a D!");
      else:
        print("You got an F!");

There is no difference in program flow or even speed when you use an elif construct. The blocks are just arranged in a nicer way. Very much like, when in Java you are using

else if(x) {
  System.out.println("Stuff")
}

instead of

else {
  if(x) {
    System.out.println("Stuff")
  }
}

The solution in your case to get 'nicer looking' code without the usage of else so much is something like:

def get_letter_grade(grade):
  if grade < 60:
    return 'F'
  if grade < 70:
    return 'D'
  if grade < 80:
    return 'C'
  if grade < 90:
    return 'B'
  return 'A'

print("Your grade: {}".format(get_letter_grade(85)))

P.S. What is wrong with you Americans? Don't you care for the alphabet? What happened to 'E'?

 

I was just wondering to myself why python would have a separate elif keyword. But of course it makes sense because of whitespace having meaning in python.
Thanks!

 

Quote from python documentation to back me up on this:

The keyword ‘elif’ is short for ‘else if’, and is useful to avoid excessive indentation.

 

Maybe I was unclear, but the reason that this is so mind blowing to me is that else if isn’t a keyword. There is only elseand if. Python had to introduce a third keyword because else if isn’t valid syntax. In other words, else if comes for free in C-like languages due to the language grammar, and I had just assumed it was a special token.

 
code of conduct - report abuse