Loops in Python

 


So far we have seen that Python executes code in a sequence and each block of code is executed once.
Loops allow us to execute a block of code several times.

While Loop

Allows us to execute a block of code several times as long as the condition is

True
.

While Loop Example

The following code snippet prints the next three consecutive numbers after a given number.

Code

a = int(input())
counter = 0
while counter < 3:
a = a + 1
print(a)
counter = counter + 1
PYTHON

Input

4

Output

5
6
7

Possible Mistakes

1. Missing Initialization

Code

a = int(input())
while counter < 3:
a = a + 1
print(a)
counter = counter + 1
print("End")
PYTHON

Input

5

Output

NameError: name 'counter' is not defined

2. Incorrect Termination Condition

Code

a = int(input())
counter = 0
condition = (counter < 3)
while condition:
a = a + 1
print(a)
counter = counter + 1
PYTHON

Input

10

Output

The above code runs into an infinite loop.

While block will keep repeating as the value in condition variable is

True
.

3. Not Updating Counter Variable

Code

a = int(input())
counter = 0
while counter < 3:
a = a + 1
print(a)
print("End")
PYTHON

Input

10

Output

Infinite Loop

As the value of counter is not updating.

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form