while
loop executes till its given condition is valid and stops execution when it's invalid. while
loops are more flexible than for
loops and they can be executed infinitely by setting the condition to True
, something that is not possible with for
loops.i = 0
my_list = [10, 20, 30, 40, 50]
## Define a while loop, till 'i' is smaller than length of 'my_list'
while i < len(my_list):
print(my_list[i]) # [10, 20, 30, 40, 50]
# similar to 'i=i+1', since 'i++' is not supported
i += 1
## Infinite looping
while True:
pass
# do something, but remember to stop at some point!