loops in python



The Python programming language provides the following types of loops to handle looping requirements. Python provides three ways to do loops. While all methods provide similar basic functionality, they differ in syntax and status check timing.

  1. While loop:

    In python, a while loop is used to repeatedly execute a block of statements until the specified condition is met. And when the condition becomes false, the line immediately after the loop in the program is executed.
    Syntax :

     while expression: statement (s) 

    All statements indented by the same number of character spaces after the program construct are considered part of the same block code. Python uses indentation as a method for grouping statements.
    Example:

    # Python program for illustration
    # loop

    count = 0

    while (count & lt; 3 ): 

    count = count + 1

    print ( " Hello Geek " )

    Output:

     Hello Geek Hello Geek Hello Geek 
    • Using else statement with c with the while icons: As discussed above, the while loop executes the block until a condition is met. When the condition becomes false, the statement immediately after the loop is executed.
      The else clause is only executed when your while condition becomes false. If you break out of the loop or an exception is thrown, it will not be executed.
      If something like this:

      if condition:

      # execute these statements

      else :

      # execute these statements

      and although the loop looks like it

      while condition:

      # execute these statements

      else :

        # execute these statements

      # Python program for illustration
      # combining the rest with while

      count = 0

      while (count & lt; 3 ): 

        count = count + 1

      print ( "Hello Geek" )

      else :

      print ( " In Else Block " )

      Output:

       Hello Geek Hello Geek Hello Geek In Else Block 
    • One while statement block: just like the if block, if the while block consists of one statement, we can declare the whole loop in one line, as below :

      # Python program for illustration
      # One statement per block

      count = 0

      while (count = = 0 ): print ( "Hello Geek" )

      Note . It is recommended to not use this type of loop as it is an infinite infinite loop where the condition is always met and you must force the compiler to quit.

    See this for an example where a while loop is used for iterators. As mentioned in the article, it is not recommended to use a while loop for iterators in python.

  2. for in Loop: For loops are used to iterate through. For example: traversing a list, string or array, and so on. There is no C style for a loop in Python, i.e. for (i = 0; i & lt; n; i ++). There is a for loop that is similar to

    # Python program for illustration
    # Loop through the list

    print ( "List Iteration" )

    l = [ "geeks" , "for" , "geeks" ]

    for i in l:

      print ( i)

     
    # Loop over a tuple (immutable)

    print ( "Tuple Iteration" )

    t = ( " geeks " , " for " , "geeks" )

    for i in t:

    print (i)

     
    # Iter String-Based Operation

    print ( "String Iteration "

    s = "Geeks"

    for i in s:

    print (i)

     
    # Looping through the dictionary

    print ( "Dictionary Iteration"

    d = dict () 

    d [ `xyz` ] = 123

    d [ ` abc` ] = 345

    for i in d:

      print ( "% s % d" % (i, d [i ]))

    Output:

     List Iteration geeks for geeks Tuple Iteration geeks for geeks String Iteration G eeks Dictionary Iteration xyz 123 abc 345 
  3. Iteration over the sequence index : we can also use the item index in sequences for iteration. The basic idea is to first calculate the length of the list and iterate over the sequence within the range of that length.
    See example below:

    # Python program to illustrate
    # Iterate through the index

     

    list = [ "geeks" , " for " , " geeks " ]

    for index in range ( len ( list )):

    print li st [index]

    Output:

     geeks for geeks 
  4. Using the else statement with for loops: We also we can combine the else statement with a for loop as in a while loop. But since there is no condition in the for loop, according to which execution will be terminated, the else block will be executed immediately after the block completes execution.
    An example below explains how to do this:

    # Python program for illustration
    # combining more c for

     

    list = [ "geeks" , "for" , "geeks" ]

    for index in range ( len ( list )):

    print list [index]

    else :

    print "Inside Else Block"

    Exit:

     geeks for geeks Inside Else Block 
  5. We can use an in loop for custom iterators. See

    for iterator_var in sequence:

    for iterator_var in sequence:

      statements (s)

      statements (s)

    Syntax for a nested while statement in Python programming language looks like this:

    while expression:

      while expression: 

    statement (s)

    statement (s)

    One final note about nesting loops is that we can put any type loop inside any other type of loop. For example, a for loop can be inside a while loop or vice versa.

    # Python program for illustration
    # nested for Python loops

    from __ future__ import print_function

    for i in range ( 1 , 5 ):

    for j in range (i):

    print (i, end = `` )

    print ()

    Exit:

     1 2 2 3 3 3 4 4 4 4 
  6. Loop control operations: Loop control statements change execution from its normal sequence ... When execution leaves a scope, all automatic objects created in that scope are destroyed. Python supports the following control statements:
    • Continue statement: returns control to the beginning of the loop.

      Exit:

       Current Letter: g Current Letter: k Current Letter: f Current Letter: o Current Letter: r Current Letter: g Current Letter: k 
    • Break Break: it takes control out of the loop

    • # Prints all letters except & # 39; e & # 39; and & # 39; s & # 39;

      for letter in `pythonengineering`

        if letter = = `e` or letter = = `s` :

      continue

      print ` Current Letter: ` , letter

      var = 10

      for letter in `pythonengineering`

       

      # break the loop as soon as it sees "e"

      # or & # 39; s & # 39;

      if letter = = `e` or letter = = `s` :

        break

        

      print ` Current Letter: ` , letter

      Output:

       Current Letter: e 
    • Pass Statement: we use pass to write empty loops. Pass is also used for empty control statement, function and classes.

      # Empty loop

      for letter in `pythonengineering` :

      pass

      print ` Last Letter: ` , letter

      Output:

       Las t Letter: s 

Exercise: How to print a list in reverse order (last to first element), using while and for loops.

This article is provided by Ashirwad Kumar. If you like Python.Engineering and would like to contribute, you can also write an article and mail it to contrib @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.
Please post comments if you find something wrong or if you would like to share more information on the topic under discussion