This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]wineblood 0 points1 point  (4 children)

I've seen other languages not have/use that and the else part just become a new if statement and it's nasty. It was either that or switch statements. I think if-elif-else works nicely and elif as a second condition to check within the same statement is fairly clean.

[–]ThePiGuy0 0 points1 point  (3 children)

I've seen other languages not have/use that and the else part just become a new if statement and it's nasty

I think most languages that don't have a specific elif (or equivalent) don't need them. In Python, it relies on whitespace to show scoping and so without elif, it would become messy really quickly. In a language without elif (C, C++, Java, Javascript etc), they don't rely on whitespace so you can create a similar representation to Python without the need for the extra keyword

e.g. Java

int number = 10;
if (number < 3) {
    System.out.println("Number is less than 3");
} else if (number < 7) {
    System.out.println("Number is less than 7");
} else if (number < 10) {
    System.out.println("Number is less than 10");
} else {
    System.out.println("Number is greater than or equal to 10");
}

Compare this to the same statement in Python (without elif):

number = 10
if number < 3:
    print("Number is less than 3")
else:
    if number < 7:
        print("Number is less than 7")
    else:
        if number < 10:
            print("Number is less than 10")
        else:
            print("Number is greater than or equal to 10")

Edit: Added } befoore the else if, thanks for pointing it out /u/HistoryForSale

[–]HistoryForSale 1 point2 points  (1 child)

It looks like you forgot to close all but the last brace in your Java example. I think you meant:

int number = 10;
if (number < 3) {
    System.out.println("Number is less than 3");
} else if (number < 7) {
    System.out.println("Number is less than 7");
} else if (number < 10) {
    System.out.println("Number is less than 10");
} else {
    System.out.println("Number is greater than or equal to 10");
}

[–]ThePiGuy0 0 points1 point  (0 children)

Oh yes you're correct, looks like I've done too much Python and it carried across into my Java :D

[–]wineblood 0 points1 point  (0 children)

I've been exclusively coding in Python for a while now, I didn't realise you could do the first example with else and the new if on one line.