-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,570
  • 16
  • 163
  • 180
Sygnerical
  • 231
  • 1
  • 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
  • 172,303
  • 28
  • 230
  • 274
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,537
  • 7
  • 33
  • 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
  • 21,988
  • 13
  • 81
  • 109
dhuang
  • 909
  • 4
  • 18