Python else Statement
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
- Position:
elseMust be the last branch of the if-elif chain. - No condition needed:
elseNo condition expression follows it. - Always executed: if none of the preceding conditions is satisfied, the else block is guaranteed to execute.
Example
Example 1: basic usage
Example
A simple either-or choice
age
=
15
if
age
=
18
:
(
"Adult"
)
else
:
(
"Minor"
)
Even or odd check
num
=
7
if
num %
2
==
0
:
(
f
"{num} is even"
)
else
:
(
f
"{num} is odd"
)
Expected output:
未成年人
7 是奇数
Code analysis:
- age = 15 does not satisfy age >= 18, so the else branch runs.
- 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"
(
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"
:
(
"Login successful"
)
else
:
(
"Login failed, please check your username or password"
)
Handle the case where the list is empty
items
=
[
]
if
items:
(
f
"The list has {len(items)} elements"
)
else
:
(
"The list is empty"
)
else in file operations
try
:
result
=
10
/
2
except
ZeroDivisionError
:
(
"Cannot divide by zero"
)
else
:
(
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 Control