-3

If I have two if statements and then an else, how do I know which if statement the else applies to? Is it by the indentation? For example this,

if x == 2:
    if y == 3:
        x = y
else:
    y = x

Which if statement does the else refer to?

Kevin B
  • 94,164
  • 15
  • 164
  • 175
Sygnerical
  • 221
  • 3
  • 12
  • 2
    In python, it will be indents. Other languages use curly braces. What you're looking for is called 'scope' – Will Aug 10 '15 at 16:13

3 Answers3

6

else applies to the first if statement, see the indentation.

Avinash Raj
  • 166,785
  • 24
  • 204
  • 249
3

You gotta look at the indentation to figure out to what which if does that else belong to.

In this case

if x == 2:
|    if y == 3:
|    |    x = y
|    |
|    else:
|         pass # example
else:
    y = x

it belongs to the if x = 2:

jramirez
  • 8,201
  • 7
  • 31
  • 46
2

First, the above code checks:

if x == 2:

If this boolean is False, the code moves to the else:

else:
     y = x

If if x == 2 is True, the code moves to the nested if-statement:

if y == 3:
     x = y

According to this page http://www.python-course.eu/python3_blocks.php, it talks about how instead of braces to group statements into blocks, Python uses indentation: "Python programs get structured through indentation, i.e. code blocks are defined by their indentation."


idk
(source: python-course.eu)

tl;dr: YES, in Python, indentation matters.
Glorfindel
  • 20,880
  • 13
  • 75
  • 99
aznbanana9
  • 869
  • 4
  • 18