Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python elif Statement

Python elif Statement

Python3 Conditional Statements Python3 Conditional Control


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


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"

print

(

f

"Grade: {grade}"

)

 

Output: Grade: B

Expected output:

成绩等级: B

Code analysis:

  1. score = 85; first check score >= 90(False)。
  2. Then continue checking score >= 80(True), and execute the corresponding code block.
  3. 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"

:

   

print

(

"You chose New File"

)

elif

choice

==

"2"

:

   

print

(

"You chose Open File"

)

elif

choice

==

"3"

:

   

print

(

"You chose Save File"

)

elif

choice

==

"4"

:

   

print

(

"You chose Exit"

)

else

:

   

print

(

"Invalid choice"

)

Expected output:

你选择了打开文件

Code analysis:

Example 3: complex combinations of conditions

Example

Multi-condition combined judgment

age

=

25

income

=

5000

if

age

<

18

:

   

print

(

"Minor"

)

elif

age

=

18

and

income

<

3000

:

   

print

(

"Adult, low income"

)

elif

age

=

18

and

income

=

3000

and

income

<

10000

:

   

print

(

"Adult, middle income"

)

elif

age

=

18

and

income

=

10000

:

   

print

(

"Adult, high income"

)

Use elif for clearer logic

status

=

"error"

if

status

==

"success"

:

   

print

(

"Operation succeeded"

)

elif

status

==

"error"

:

   

print

(

"Operation failed"

)

elif

status

==

"warning"

:

   

print

(

"Warning"

)

elif

status

==

"info"

:

   

print

(

"Info"

)

Expected output:

成年人,中等收入
操作失败

elif makes code with multiple conditional branches clearer and easier to read.


Python3 Conditional Statements Python3 Conditional Control