DEV Community

Discussion on: The Ultimate Python Cheatsheet

Collapse
ejm profile image
EJM97

There seems to be an syntax issue in the Nested if-else Statement. 1 if but 2 else statements.

Collapse
abhirajb profile image
Abhiraj Bhowmick Author

That is not a syntax error. That is called nesting in computer programming. Any number of these statements can be nested inside one another. If I would give only one else statement then there would not be any difference between nested statements and normal if-else statements
Hope I was able to clear it for you :)

Collapse
ejm profile image
EJM97

Apprecieate the explanation, but unfortunately I still don't get it. Could you please explain further, my current understanding of nested if statements is as follows.

if condition 1:
    statements
    # a nested if-else
    if condition 2:
        statements
    else:
        statements
else:
    statements
    # another nested if-else     
    if condition 3:
        statements
    else:
        statements    

I tried using 2 else statements witihn one 'if' indented in diferrent ways but it always threw an error.
for exaple i tried -->

if condition 1:
    statements
    else:
        statements
else:
    statements

Using 2 else statements after a single if seems logically pointless even if it were syntactically correct as all the statements under both else conditions seems to be executed only when the if condition is False