while loops are used when a specific task is supposed to be executed until a specific condition is met. while loops are commonly used to execute code in an infinite loop. Let's look at a specific example where we would like to print the value of i from 0 to 9:
i=0
while i<10:
print("The value of i is ",i)
i+=1
Inside the while loop, we increment i by 1 for every iteration. The value of i is incremented as follows:
i += 1
This is equivalent to i = i+1.
This example would execute the code until the value of i is less than 10. It is also possible to execute something in an infinite loop:
i=0
while True:
print("The value of i is ",i)
i+=1
The execution of this infinite loop can be stopped by pressing Ctrl + C on your keyboard.
It is also possible to have nested while loops:
i=0
j=0
while i<10:
while j<10:
print("The value of i,j is ",i,",",j)
i+=1
j+=1
Similar to for loops, while loops also rely on the indented code block to execute a piece of code.