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.
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])
0 Response to "7. Python Loops"
Post a Comment