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

Python for-else Loop

Python for-else Loop

Python3 Loop Statements Python3 loop statements


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


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

:

       

print

(

f

"Found an even number: {num}"

)

       

break

else

:

   

print

(

"No even number found"

)

print

(

"---"

)

The case where the list contains even numbers

numbers

=

[

1

,

3

,

6

,

7

,

9

]

for

num

in

numbers:

   

if

num %

2

==

0

:

       

print

(

f

"Found an even number: {num}"

)

       

break

else

:

   

print

(

"No even number found"

)

Expected output:

未找到偶数
---
找到偶数: 6

Code analysis:

  1. In the first example, the whole list is traversed (no break), so else executes.
  2. 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

:

           

print

(

f

"{n} is not prime; it is divisible by {i}"

)

           

return

False

   

else

:

       

The loop ended normally, meaning no divisor was found

       

print

(

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

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=== Without break ==="

)

Another form of writing it (without 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 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

print

(

"=== Checking for failing scores ==="

)

for

score

in

scores:

   

if

score

<

60

:

       

print

(

f

"Found a failing score: {score}"

)

       

break

   

print

(

f

"{score} points, passing"

)

else

:

   

print

(

"All scores are passing"

)

Another scenario: perform clean-up after all processing is done

print

(

"\n=== Clean-up after processing ==="

)

files

=

[

"a.txt"

,

"b.txt"

,

"c.txt"

]

for

file

in

files:

   

print

(

f

"Processing file: {file}"

)

else

:

   

print

(

"All files processed, performing clean-up"

)

   

print

(

"--- 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"

   

}

   

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 traversing all users with no match

       

print

(

"Incorrect username or password"

)

       

return

False

Testing

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


Python3 Loop Statements Python3 loop statements