Do you have issues with while loops in Python?

I am about 3 months in to a lot of programming. Actually just beginning to dive into object oriented programing in Python. I have been reviewing some of the basic concepts of Python and thought about sharing one little comment about the while loop. They are probably be the trickiest one in Python. At least it is to me. It is easy to write an infinite loop using a WHILE loop. Enjoy the simple example to understand counting within the loop.

Code block1: produce infinite loop

 counter=10

while counter<=10:

print (counter)

Code block 2: Right way to implement WHILE loop, change your counter within the loop.

counter=10
while counter>=0:
print (counter)
counter=counter-1

counter=0

while counter<=10:
print (counter)
counter=counter+1

 

Output for Code block 2

>>>
10
9
8
7
6
5
4
3
2
1
0
0
1
2
3
4
5
6
7
8
9
10
>>>

# Example of an infinite loop

health=20
trolls=0
damage=3
while health!=0: # condition is never met as 10-3 series does not produce 0
trolls+=1 #we are not modifying the right counter
health=health-damage
print (health, damage, trolls)

# Fixing the infinite loop: Make sure that the condition becomes false

Download the Python script if you like [wpdm_file id=1]

health=20
trolls=0
damage=2
while health!=0: # condition is never met as 10-3 series does not produce 0
trolls+=1 #we are not modifying the right counter
health=health-damage
print (health, damage, trolls)

Leave a Comment

Your email address will not be published. Required fields are marked *