Python for-else Loop
In Python,fora loop can have anelseelse clause, which is Python-specific syntax, unlike most other programming languages.
for-elseStructure: when the loop completes normally (i.e., is notbreakinterrupted by break), executeelsethe code in the else clause.
Word Meaning: elseelse means "other"; here it means "processing after the loop ends normally".
Basic Syntax and Parameters
Syntax Format
for 变量 in 可迭代对象:
循环体
else:
循环正常结束时的处理
Execution Logic
- Normal Completion: After the loop has iterated through all elements, the else clause is executed.
- Terminated by break: If the loop is interrupted by break, the else clause is not executed.
- Abnormal Termination: If an exception occurs in the loop, else is not executed either.
Examples
Example 1: Basic Usage - Execute When Search Fails
Example
numbers = [1, 3, 5, 7, 9]
for num in numbers:
if num % 2 == 0:
print(f"Found even number: {num}")
break
else:
print("No even number found")
print("---")
# Case where the list contains an even number
numbers = [1, 3, 6, 7, 9]
for num in numbers:
if num % 2 == 0:
print(f"Found even number: {num}")
break
else:
print("No even number found")
Expected output:
未找到偶数 --- 找到偶数: 6
Code explanation:
- First example: after iterating through the entire list (without executing break), else is executed.
- Second example: after finding an even number, break is executed, skipping else.
Example 2: Common Application - Finding Prime Numbers
Example
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
print(f"{n} is not a prime number, it is divisible by {i}")
return False
else:
# The loop ends normally, meaning no factor was found
print(f"{n} is a prime number")
return True
# Test
is_prime(7) # Output: 7 is a prime number
is_prime(10) # Output: 10 is not a prime number, it is divisible by 2
Expected output:
7 是质数 10 不是质数,能被 2 整除
This is one of the most classic uses of for-else: after the search traversal is complete, if the target is not found, execute else.
Example 3: Comparison with break
Example
fruits = ["apple", "banana", "orange", "grape"]
# Using for-else
print("=== Using for-else ===")
for fruit in fruits:
if fruit == "orange":
print(f"Found: {fruit}")
break
print(f"Checking: {fruit}")
else:
print("Target not found")
print("\n"=== Not using break ===")
# Another way (without using else)
found = False
for fruit in fruits:
if fruit == "orange":
print(f"Found: {fruit}")
found = True
break
print(f"Checking: {fruit}")
if not found:
print("Target not found")
Expected output:
=== 使用 for-else === 检查: apple 检查: banana 找到: orange === 不使用 else === 检查: apple 检查: banana 找到: orange
The for-else syntax is more concise and does not require an extra flag variable.
Example 4: Handling Loop Completion
Example
scores = [85, 90, 78, 92, 88]
# Check if there are any failing grades
print("=== Check if there are any failing grades ===")
for score in scores:
if score < 60:
print(f"Found failing grade: {score}")
break
print(f"{score} points, pass")
else:
print("All grades pass")
# Another scenario: perform cleanup after all processing is complete
print("\n"=== Cleanup after processing is complete ===")
files = ["a.txt", "b.txt", "c.txt"]
for file in files:
print(f"Processing file: {file}")
else:
print("All files have been processed, performing cleanup work")
print("--- Cleanup complete ---")
Expected output:
=== 检查是否有不及格 === 85 分,合格 90 分,合格 78 分,合格 92 分,合格 88 分,合格 所有成绩都及格 === 处理完成后清理 === 处理文件: a.txt 处理文件: b.txt 处理文件: c.txt 所有文件处理完成,执行清理工作 --- 清理完成 ---
for-else can also be used in scenarios where you "perform cleanup after completion".
Example 5: Practical Application - Login Verification
Example
def try_login(username, password):
valid_users = {
"admin": "123456",
"user": "password",
"guest": "guest"
}
print(f"Attempting login: {username}")
for user, pwd in valid_users.items():
if user == username and pwd == password:
print("Login successful!")
return True
else:
# After iterating through all users, no match was found
print("Incorrect username or password")
return False
# Test
try_login("admin", "123456") # Output: Login successful
print("---")
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
elseelse is notifpart of if, but ratherforpart of for.- Don't
elseandifconfuse for-else with if-else. - This syntax is unique to Python; other languages don't have it.
Other Extensions
Python3 Loop Statements