Python Tutorial 09: Looping in Python

Python support following type of loops:

  • “While” Loop
  • For Loop

While Loop

Syntax : While <Condition True>

Example

[vtftable ]
def CountDown():{;n}     i = 10 {;n}     while i>=0: {;n}          print(i, end= ‘ ‘) {;n}          i = i – 1 {;n}    print() {;n}    print (‘Done!’, end= ‘ ‘);;;Function Name{;n}Initial Value{;n}While condition is true do{;n}Things to do in each iteration{;n}Raise the counter by i{;n}After The Loop{;n};nn;;nn;;nn;
[/vtftable]

Result

For Loop ()

For <Variable> in Range(<Start Number>, <End Number>, Step-by)

Let’s rewrite the previous example  (Countdown) function using a For Loop

[vtftable ]
def CountDown_Using_For_Loop():{;n}    for i in range(10,0,-1):{;n}        print (i, end = ‘ ‘ ){;n}    print(){;n}    print(‘Done!’);;;Function Name{;n}For Loop statement.*{;n}Statement insider the For Loop{;n}Statement after the for loop;;; ;;; ;nn;;nn;;nn;

[/vtftable]

Note:

The for loop statement will firstly assignment to the variable in using the range function.  The Range function create a sequences from the first argument to the second argument with stepping up or down by the instruction given from the third argument.

In this example:

Range (10, 0,-1)

We are creating a sequences starting from 10 stepping down by 1 to the value just before 0 (i.e. 1)

Following is the result

For Loop Vs While Loop

While loop:

  1. It checked the condition before entering to the iteration. If the condition failed, it not execute the iteration.
  2. If the condition didn’t change during the iteration, then the loop will most likely be looped infinitely.

For Loop

  1. It does not check the condition before entering to the iteration. It simply assign a value to a counter and start it’s first iteration. It only check the condition at the end of each iteration.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Exit mobile version