Python - Loop else block

Introduction

Loop else block runs if and only if the loop is exited normally, i.e., without hitting a break.

The following code determines whether a positive integer y is prime by searching for factors greater than 1:

Demo

y = 13
x = y // 2                                # For some y > 1 
while x > 1: 
    if y % x == 0:                        # Remainder 
        print(y, 'has factor', x) 
        break                             # Skip else 
    x -= 1 # w ww  .jav  a  2s. c  o  m
else:                                     # Normal exit 
    print(y, 'is prime')

Result

The code inserts a break where a factor is found.