Block of code executes over and over again till the condition is True.
spam = 0
while spam < 5:
print("Hello world")
spam = spam + 1
When the execution is run through a loop, it is called an iteration.
The while loop iterated 5 times because spam starts at 0 and at each iteration spam increases by 1. After the fifth iteration, spam is set to 5 which makes the condition spam < 5 False and the while terminates. The execution just continues on with the rest of the program
When the execution is run through a loop, it is called an iteration.
name = ''
while name != 'your name': #For the first condition, condition is True because blank string does not equal 'your name'.
print('Please type your name')
name = input()
print('Thank you')
Loops can be used to do input validation.
while(True):
print('Hello')
Above code will be executed infinite times since the condition is always True because the value True will always evaluate to the value True. To stop the execution press Ctrl + C.
The break causes the execution to immediately jump out of the loop.
name = ''
while True: #infinite loop
print('Please type your name')
name = input()
if name == 'your name':
break
print('Thank you')
In the above program, we will never 'break out' of the loop because the condition always is True. So, we have a break statement inside the loop and it is the break statement that causes the execution to immediately jump out of this loop and continue on with the rest of program.
When the program execution reaches the continue statement, the execution immediately jumps back to the start of the loop and reevaluates the loops condition.
spam = 0
while spam < 5:
spam = spam + 1
if spam == 3:
continue
print("Spam is " + str(spam)) #since spam is an integer, it is converted to string so it can be concatenated.