Python Loops

Published:2018-12-04
Share:

Loops allow you to execute a statement or group of statements repeatedly. Loop Architecture Python programming language has two typed of loop

while loop

Repeats a statement or group of statements while a given condition is True. It tests the condition before executing the loop body.

for loop

Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

 

Loop Control

The Loop control statements change the execution from its normal sequence. When the execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements.

 

Control Keywords

  • break

    breaks the loop routine and python would run the statement right after the loop
  • continue

    continues the loop from the beginning , skipping the rest of the statement within the loop.
  • pass

    pass is not strictly a loop control, its a general keyword used for "Do nothing" just syntactically used.
  •  

#!/usr/bin/env python

list = [1,2,3,4]

it = iter(list) 


# printing items of the iterator
for x in it:
   print (x)
 


# you can printing items of the list directly
for x in  list:
   print (x)
 



# printing  the first item only
for x in it:
   print (x)
  break
 
  


# printing  nothing
for x in it:
   break
   print (x)
 



# printing  nothing
for x in it:
   continue
   print (x)
 

   
# you can use next() function
while True:
   try:
      print (next(it), end=' ')
   except StopIteration:
      pass

Read also

Python Decision Making

Decision-making is the way where a program shift execution from one side to another based on a condition if the condition evaluates to True then the next statement(s) will be executed other wise if there is any else  statement its block(or body) will be executed instead.   True vs False vs not True All non 'None' values, not empty string, non-zero numbers, whitspace-only strings, and not False values are True False All None, empty string, False values are conside...