Python elif Statement
elif is the keyword in Python used for multi-condition judgment; it is short for "else if".
When several conditions need to be handled,elif allows us to chain multiple condition checks into a complete branching structure.
Word meaning: elif is short for "else if", meaning "otherwise if".
Basic syntax and parameters
elif It must be used together with if and cannot stand alone.
Syntax format
if 条件1:
代码块1
elif 条件2:
代码块2
elif 条件3:
代码块3
else:
代码块4
Syntax Description
- Order of condition checks: checks are made from top to bottom; when the first True condition is found, its code block is executed and the remaining branches are skipped.
- No limit on quantity:
elifThere is no limit on the number; you can add as many as needed. - Optional else:
elseis optional and executes when none of the conditions is satisfied.
Example
Example 1: basic multi-condition judgment
Example
Grade classification system
score
=
85
if
score
=
90
:
grade
=
"A"
elif
score
=
80
:
grade
=
"B"
elif
score
=
70
:
grade
=
"C"
elif
score
=
60
:
grade
=
"D"
else
:
grade
=
"F"
(
f
"Grade: {grade}"
)
Output: Grade: B
Expected output:
成绩等级: B
Code analysis:
- score = 85; first check
score >= 90(False)。 - Then continue checking
score >= 80(True), and execute the corresponding code block. - Once a match succeeds, the whole if-elif chain is exited immediately.
Example 2: string matching
Example
A simple menu choice
choice
=
"2"
if
choice
==
"1"
:
(
"You chose New File"
)
elif
choice
==
"2"
:
(
"You chose Open File"
)
elif
choice
==
"3"
:
(
"You chose Save File"
)
elif
choice
==
"4"
:
(
"You chose Exit"
)
else
:
(
"Invalid choice"
)
Expected output:
你选择了打开文件
Code analysis:
- elif is used for branching among multiple options.
- The branches are mutually exclusive; only the first matching condition is executed.
Example 3: complex combinations of conditions
Example
Multi-condition combined judgment
age
=
25
income
=
5000
if
age
<
18
:
(
"Minor"
)
elif
age
=
18
and
income
<
3000
:
(
"Adult, low income"
)
elif
age
=
18
and
income
=
3000
and
income
<
10000
:
(
"Adult, middle income"
)
elif
age
=
18
and
income
=
10000
:
(
"Adult, high income"
)
Use elif for clearer logic
status
=
"error"
if
status
==
"success"
:
(
"Operation succeeded"
)
elif
status
==
"error"
:
(
"Operation failed"
)
elif
status
==
"warning"
:
(
"Warning"
)
elif
status
==
"info"
:
(
"Info"
)
Expected output:
成年人,中等收入
操作失败
elif makes code with multiple conditional branches clearer and easier to read.
Python3 Conditional Control