Python Loop
Loop
Python has two primitive loop commands:
• while loops
• for loops
The while Loop
With the while loop we can execute a set of statements as long as a condition is true.
EX: Print X as long as X is less than 6:
X=1
while X < 6:
print(X)
X += 1
Exit the loop when X is 3
X=1
while X < 6:
print(X)
if X == 3:
break
X += 1
Continue to the next iteration if X is 3:
X=0
while X < 6:
X += 1
if X == 3:
continue
print(X)
Note that number 3 is missing in the result
The else Statement
With the else statement we can run a block of code once when the condition no longer
is true:
EX: Print a message once the condition is false:
X=1
while X < 6:
print(X)
X += 1
else:
print("X is no longer less than 6")
Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, adictionary,
a set, or a string).
This is less like the for keyword in other programming languages, and works more like
an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list,
tuple.
Looping Through a String
EX : Even strings are iterable objects, they contain a sequence of characters:
for x in "banana":
print(x)
The break Statement
With the break statement we can stop the loop before it has looped through all the
items:
EX: Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break