DEV Community

Discussion on: The `else if` Keyword Doesn’t Exist in Java

Collapse
 
donut87 profile image
Christian Baer

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'?

Collapse
 
silwing profile image
Silwing

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!

Collapse
 
donut87 profile image
Christian Baer

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.

Collapse
 
renegadecoder94 profile image
Jeremy Grifski • Edited

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.

Collapse
 
_hs_ profile image
HS

gave a heart just beacuse of P.S. :D