Hi,

I have a very simple question:


first of all, my code:

import os

def test():
    x = "Linux"
    y = "Windows"

    if os.name == "posix":
        print(x)
    if os.name == "nt":
        print(y)
    else:
        print("there is a problem")

Run that code on Linux (don't know about windows) and it'll print both Linux and there is a problem.

Now do this:

import os

def test():
    x = "Linux"
    y = "Windows"
     if os.name == "posix":
        print(x)
    elif os.name == "nt":
        print(y)
    else:
        print("there is a problem")

This time it'll work perfectly. The question is: why does it work with elif but not with two if's?

I was told that it was the same, only that elif is more elegant, but know I see there must be a difference. Any thoughts?


Thank you

Well, in your situation, they are the same:
Let's look at this:

if True:
    print("A")
elif True:
    print("B")

Would display A.

Now this:

if True:
    print("A")
if True:
    print("B")

Would display
A
B

Get it?
Of course, in your situation, os.name can't be two things at once, and elif is just more elegant, it's just more pythonic, conforms more to idioms.

Python's if...elif...elif...elif...elif...elif...elif...else is relatively similar to (C/C++/C#)'s switch...case...case...case...case...case...default You would usually have a bunch of elif's instead of a bunch of if's,
just like a case/switch/default is more readable in other languages.

Ok, I get the if and elif stuff, now, why is it printing both values if OS is supposed to be posix an only posix? And why is it solved with elif, if, as you say it's supposed to mean the same as if-if?

yes, yes I understand that, but if you check my code you'll see that two ifs in Linux will output BOTH Linux and there is a problem, whereas one if, one elif and one else will only output Linux, which should be the case...

In your code the else pairs up with the if statement just before it. If you change that to elif it pairs up with the if before that. That's because all the conditional statements have the same indentation level.

Oh! I see now. Excellent explanation, thank you. So, after all there is a slight difference in that elseif does not pair up with anything?

elif can follow only if or other elif on same indention level

Ok I see, what about else? It can follow either an if or an elif, right?

Thats right, and while or for.

OK, I understand now. It's working perfectly. Thak you guys, you're realy helpful.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.