7. Python Loops


In Programming, there might be situation that you need to execute particular block of code multiple times. Python loop provides various structures to allow us executing a statement or a block of statements. The following are loops in Python.

7.1 While Loop

Python while loop will repeat a statement or a block of statements if the given condition is true. So the way of while loop works is it tests the condition at beginning. 

while condition:
    statement(s)

When the condition is true the statement(s) will be executed, but if the condition is false it will not.
# while-loop1
count = 1
while count <= 10:
    print(count, end=' ')
    count = count + 1
# while-loop2
count = 10
while count > 10:
    print(count, end=' ')
    count = count + 1

In while-loop1 the count is tested wether the condition is true, so yes the given condition is true while the count <= 10, but when count reached 11 the condition become false then program control will passes the loop. In while-loop2 the statement will not be executed because the given condition is false.

Sometimes when you are using while loop, there is a condition of loop that not altered to be false and the statement(s) will be executed infinitely, we usually call this term as inifinite loop. This usually happened for beginners when they forgot to put a statement that can alter condition. Let's try with our previous example.
count = 1
while count <= 10:
    print(count)

When you forget to put count = count + 1 in the program above it will be infinite loop because the count condition will always be 1. You can stop the infinite loop with CTRL+C.

7.2 For Loop

Python for loop iterate each item in sequence such as string, list, tuple, set, and dictionary. 

for element in sequence:
    statement(s) 

The item from the sequence will be assigned to element then statement block is executed until the sequence is exhausted. Some examples Python for loop.
# example using range()
for elmt in range(10):
    print(elmt, end=' ') 

print("\n"+"=" * 20)  

# example using list 
words = ['eat', 'sleep', 'code']
for w in words:
    print(w, len(w)) 

print("=" * 20)
# iterate over the indices of a sequence
for i in range(len(words)):
    print(i, words[i]) 

7.3 Break and Continue Statement

You can gain more control from loop's normal way with break and continue statement. Here break statement will terminate the loop in certain condition but continue statement will skip the rest of it's block statement then go back to reiterate again.
fruits = ['banana', 'mango', 'melon', 'apple', 'pineaple']
for fruit in fruits:
    # when this condition is met, the loop terminated
    if fruit == 'melon':
        break 
    print(fruit)

print("=" * 20)

for fruit in fruits:
    # this will skip the rest of the code 
    if fruit == 'melon':
        continue
    print(fruit)

7.4 Pass Statement

Python pass statement will do nothing in the code when executed, it's just useful to put pass statement in block of code that hasn't been written yet.

fruits = ['banana', 'mango', 'melon', 'apple', 'pineaple']
for fruit in fruits:
    if fruit == 'melon':
        pass # nothing to do yet
    print(fruit)

7.5 Else Clause

In Python, it supports else clause for while loop and for loop. The only different is when else clause is used with while loop, the else clause will be executed if the condition become false, in for loop the else clause will be executed after the for loop has exhausted iterating the sequence. 

count = 1
while count <= 5:
    print(count)
    count += 1
else:
    # it will be executed when condition become false
    print("Else from while loop.") 

fruits = ['orange', 'mango', 'banana', 'melon']
for fruit in fruits:
    print(fruit)
else:
    # it will be executed after iterating all the sequence
    print("Else from for loop.")

Subscribe to receive free email updates:

0 Response to "7. Python Loops"

Post a Comment