Conditional statements¶
The code block after the first true condition of an if
or elif
statement
is executed. If none of the conditions are true, the code block after the
else
is executed:
1>>> x = 1
2>>> if x < 1:
3... x = 2
4... y = 3
5... elif x > 1:
6... x = 4
7... y = 5
8... else:
9... x = 6
10... y = 7
11...
12>>> x, y
13(6, 7)
Python uses indentations to delimit blocks. No explicit delimiters such as brackets or curly braces are required. Each block consists of one or more statements separated by line breaks. All these statements must be at the same indentation level.
- Line 5
The
elif
statement looks like theif
statement and works in the same way, but with two important differences:elif
is only allowed after anif
statement or anotherelif
statementyou can use as many
elif
statements as you need
- Line 8
The optional
else
clause denotes a code block that is only executed if the other conditional blocks,if
andelif
, are all false.