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?
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?
else
applies to the first if
statement, see the indentation.
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:
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."