while Loop
An if
statement is run once if its condition evaluates to TRUE
and never if it evaluates to FALSE
.
A while
statement is similar, except it can be run more than once. The statements inside it are repeatedly executed as long as the condition holds. Once it evaluates to FALSE
, the next section of code is executed.
i = 1 while i<=4: print (i) i+=1 print ('End')
Output:
>>> 1 2 3 4 End >>>
The infinite loop is a particular kind of the while
loop; it never stops running. Its condition always remains TRUE
.
while 1 == 1: print ('in the loop')
To end the while
loop prematurely, the break statement can be used.
The break statement causes the loop to finish immediately when encountered inside a loop.
i = 0 while 1==1: print (i) i += 1 if i >=3: print('breaking') break; print ('finished')
Output:
>>> 0 1 2 3 breaking finished >>>
Another statement that can be used within loops is continue.
Unlike break, continue jumps back to the top of the loop rather than stopping it.
i = 0 while True: i+=1 if i == 2: printf ('skipping 2') continue if i == 5: print ('breaking') break print (i) print ('finished')
Output:
>>> 1 skipping 2 3 4 breaking finished >>>
for Loop
n = 9 for i in range (1,5): ml = n * i print ("{} * {} = {}".format (n, i, ml))
Output:
>>> 9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 >>>