+91 81900 98289

Python While Loops

This Python While Loops lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

A while loop repeats as long as its test stays true. Change something inside the loop or it never ends.

break leaves the loop early. continue skips to the next test.

Example 1: Start here

If the printed numbers never change, the test is not moving toward false.

n = 3 # a whole number while n > 0: # keep repeating while this stays true print(n) n -= 1 # update the stored value print("Go")

Example 2: Count down

The loop stops when n is no longer greater than 0. Forgetting n -= 1 would loop forever.

n = 3 # a whole number while n > 0: # keep repeating while this stays true print(n) n -= 1 # update the stored value

Example 3: Stop with break

break leaves the loop immediately.

n = 0 # a whole number while True: # keep repeating while this stays true n += 1 # update the stored value if n == 3: # run the indented lines only when this is true break # leave the loop now print(n)

Example 4: Skip with continue

continue jumps to the next test, so 2 is not printed.

n = 0 # a whole number while n < 4: # keep repeating while this stays true n += 1 # update the stored value if n == 2: # run the indented lines only when this is true continue # skip the rest of this turn print(n)
If the printed numbers never change, the test is not moving toward false.
Call Now 81900 98289