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

Python else Statement

Python else Statement

Python3 Conditional Statements Python3 Conditional Control


else is the keyword in Python used to handle all other cases.

else The statement is used together with if and elif ; when none of the preceding conditions is satisfied, the else code in the code block is executed.

Word meaning: else means "other", representing the case where none of the conditions is satisfied.


Basic syntax and parameters

else It must be used together with if Used as the closing part of the whole conditional structure.

Syntax format


if 条件:
    代码块1
else:
    代码块2

Syntax Description


Example

Example 1: basic usage

Example

A simple either-or choice

age

=

15

if

age

=

18

:

   

print

(

"Adult"

)

else

:

   

print

(

"Minor"

)

Even or odd check

num

=

7

if

num %

2

==

0

:

   

print

(

f

"{num} is even"

)

else

:

   

print

(

f

"{num} is odd"

)

Expected output:

未成年人
7 是奇数

Code analysis:

  1. age = 15 does not satisfy age >= 18, so the else branch runs.
  2. 7 % 2 = 1, which is not 0, so the else branch runs.

Example 2: used with elif

Example

A complete if-elif-else structure

score

=

55

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

"Score: {score}, Grade: {grade}"

)

Output: Score: 55, Grade: F

Expected output:

分数: 55, 等级: F

else acts as the final "catch-all" branch, handling all cases that do not satisfy the preceding conditions.

Example 3: handling exceptional cases

Example

Login verification example

username

=

"admin"

password

=

"wrong"

if

username

==

"admin"

and

password

==

"123456"

:

   

print

(

"Login successful"

)

else

:

   

print

(

"Login failed, please check your username or password"

)

Handle the case where the list is empty

items

=

[

]

if

items:

   

print

(

f

"The list has {len(items)} elements"

)

else

:

   

print

(

"The list is empty"

)

else in file operations

try

:

    result

=

10

/

2

except

ZeroDivisionError

:

   

print

(

"Cannot divide by zero"

)

else

:

   

print

(

f

"Calculation result: {result}"

)

Expected output:

登录失败,请检查用户名或密码
列表为空
计算结果: 5.0

else can also be used in a try-except structure to handle the case where no exception occurs.


Python3 Conditional Statements Python3 Conditional Control