Python: for, while, Loops

By Xah Lee. Date: . Last updated: .

“for” loop

Example of “for” loop:

# -*- coding: utf-8 -*-
# python

aa = range(1, 10) # creates a list, 1 to 9
for xx in aa:
    print xx                    # prints 1 to 9
# -*- coding: utf-8 -*-
# python

print range(7)                  # [0, 1, 2, 3, 4, 5, 6]
print range(3, 7)               # [3, 4, 5, 6]
print range(3, 7, 2)            # [3, 5]

“while” Loop

#-*- coding: utf-8 -*-
# python

x = 1
while x <= 9:
    print x
    x += 1

Exit Loop

Use break or continue to exit loop.

Here's a example of using break.

#-*- coding: utf-8 -*-
# python

for x in range(1, 10):          # 1 to 9
    print x
    if x == 4:
        break                   # prints 1 to 4