Python for-else Loop
In Python,for A loop can have an else clause, which is syntax unique to Python and different from most other programming languages.
for-else The structure means: when the loop completes normally (i.e. is not break interrupted), the code in else is executed.
Word meaning: else means "other", here meaning "handling after the loop ends normally".
Basic syntax and parameters
Syntax format
for variable in iterable:
循环体
else:
循环正常结束时的处理
Execution logic
- Completes normally: after the loop has traversed all elements, the else clause is executed.
- Terminated by break: if the loop is interrupted by break, the else clause is not executed.
- Terminated by an exception: if an exception occurs in the loop, else is not executed either.
Example
Example 1: basic usage - executing when a search fails
Example
Find the even numbers in a list, print them if found, otherwise execute else
numbers
=
[
1
,
3
,
5
,
7
,
9
]
for
num
in
numbers:
if
num %
2
==
0
:
(
f
"Found an even number: {num}"
)
break
else
:
(
"No even number found"
)
(
"---"
)
The case where the list contains even numbers
numbers
=
[
1
,
3
,
6
,
7
,
9
]
for
num
in
numbers:
if
num %
2
==
0
:
(
f
"Found an even number: {num}"
)
break
else
:
(
"No even number found"
)
Expected output:
未找到偶数
---
找到偶数: 6
Code analysis:
- In the first example, the whole list is traversed (no break), so else executes.
- In the second example, break is executed after finding an even number, so else is skipped.
Example 2: common application - finding prime numbers
Example
Determine whether a number is prime
def
is_prime
(
n
)
:
if
n
<=
1
:
return
False
for
i
in
range
(
2
,
int
(
n **
0.5
)
1
)
:
if
n % i
==
0
:
(
f
"{n} is not prime; it is divisible by {i}"
)
return
False
else
:
The loop ended normally, meaning no divisor was found
(
f
"{n} is prime"
)
return
True
Testing
is_prime
(
7
)
Output: 7 is prime
is_prime
(
10
)
Output: 10 is not prime; it is divisible by 2
Expected output:
7 是质数
10 不是质数,能被 2 整除
This is one of the most classic uses of for-else: after a search completes, else runs if the target was not found.
Example 3: comparison with break
Example
Scenario: traverse a list looking for a specific element
fruits
=
[
"apple"
,
"banana"
,
"orange"
,
"grape"
]
Using for-else
(
"=== Using for-else ==="
)
for
fruit
in
fruits:
if
fruit
==
"orange"
:
(
f
"Found: {fruit}"
)
break
(
f
"Checking: {fruit}"
)
else
:
(
"Target not found"
)
(
"\n=== Without break ==="
)
Another form of writing it (without else)
found
=
False
for
fruit
in
fruits:
if
fruit
==
"orange"
:
(
f
"Found: {fruit}"
)
found
=
True
break
(
f
"Checking: {fruit}"
)
if
not
found:
(
"Target not found"
)
Expected output:
=== 使用 for-else ===
检查: apple
检查: banana
找到: orange
=== 不使用 else ===
检查: apple
检查: banana
找到: orange
The for-else syntax is more concise and does not need an extra flag variable.
Example 4: handling loop completion
Example
Scenario: verify whether all elements satisfy a condition
scores
=
[
85
,
90
,
78
,
92
,
88
]
Check whether any score is failing
(
"=== Checking for failing scores ==="
)
for
score
in
scores:
if
score
<
60
:
(
f
"Found a failing score: {score}"
)
break
(
f
"{score} points, passing"
)
else
:
(
"All scores are passing"
)
Another scenario: perform clean-up after all processing is done
(
"\n=== Clean-up after processing ==="
)
files
=
[
"a.txt"
,
"b.txt"
,
"c.txt"
]
for
file
in
files:
(
f
"Processing file: {file}"
)
else
:
(
"All files processed, performing clean-up"
)
(
"--- Clean-up complete ---"
)
Expected output:
=== 检查是否有不及格 ===
85 分,合格
90 分,合格
78 分,合格
92 分,合格
88 分,合格
所有成绩都及格
=== 处理完成后清理 ===
处理文件: a.txt
处理文件: b.txt
处理文件: c.txt
所有文件处理完成,执行清理工作
--- Cleanup complete ---
for-else can also be used in "perform clean-up after completion" scenarios.
Example 5: practical application - login verification
Example
Simulate a login attempt
def
try_login
(
username
,
password
)
:
valid_users
=
{
"admin"
:
"123456"
,
"user"
:
"password"
,
"guest"
:
"guest"
}
(
f
"Attempting login: {username}"
)
for
user
,
pwd
in
valid_users.
items
(
)
:
if
user
==
username
and
pwd
==
password:
(
"Login successful!"
)
return
True
else
:
After traversing all users with no match
(
"Incorrect username or password"
)
return
False
Testing
try_login
(
"admin"
,
"123456"
)
Output: Login successful
(
"---"
)
try_login
(
"admin"
,
"wrong"
)
Output: Incorrect username or password
Expected output:
尝试登录: admin
登录成功!
---
尝试登录: admin
用户名或密码错误
for-else is very useful in traversal and search scenarios, clearly expressing the "not found" logic.
Notes
elseEitherifpart of, but ratherforpart of.- Do not confuse
elseandifwith each other. - This syntax is unique to Python; other languages do not have it.
Python3 loop statements