For Loop
# Prints: 3,5,7 nums = [3, 5, 7] for num in nums: print(num)
While Loop
# Prints: 0,1,2,3,4 counter = 0 while counter < 5: print(counter) counter += 1 # the same as counter = counter + 1
'break' statement in the loop
# Prints: 0,1,2,3,4 counter = 0 while True: print(counter) counter += 1 if counter >= 5: break # Stop the infinite While Loop
'continue' statement in the loop
# Prints only odd numbers: 1,3,5,7,9 for num in range(10): if num % 2 == 0: # Check if num is even continue # Continue to the next step in the loop and skip the rest of the code in this step print(num)
For Loop with 'else' clause
We can use 'else' for loops. When the loop condition of 'for' or 'while' statement fails then code part in 'else' is executed. If break statement is executed inside for loop then the 'else' part is skipped. Note that 'else' part is executed even if there is a continue statement.
# Prints: 1,2,3,4 for i in range(1, 10): if(i%5==0): break print(i) else: print('this is not printed because for loop is terminated because of break but not due to fail in condition')
While Loop with 'else' clause
# Prints: 0,1,2,3,4 and then it prints 'counter value reached 5' counter = 0 while(counter<5): print(counter) counter +=1 else: print('counter value reached %d' %(counter))