Python While Loop Syntax and Examples

Published on Mar 01, 2022

In computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.

Table of Contents
Syntax

while expression:
    statement/s
Examples

Basic:

count = 0

while (count < 10):
   print 'The count is:', count
   count = count + 1

Single line:

n = 5

while n > 0: n -= 1; print(n)

With else:

count = 0

while count < 5:
    print("inside loop")
    count = count + 1
else:
    print("inside else")