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
elifstatement looks like theifstatement and works in the same way, but with two important differences:elifis only allowed after anifstatement or anotherelifstatementyou can use as many
elifstatements as you need
- Line 8
The optional
elseclause denotes a code block that is only executed if the other conditional blocks,ifandelif, are all false.