Loops or Iterations in Python

while loop:

While loop executes repeatedly the block of code until the condition becomes false.

Sample Code:

strNumber = input(
    'Please Enter a Number'
);
intNumber = int( strNumber );
while intNumber > 0 :
    print( intNumber );
    intNumber = intNumber - 1;
print( 'Thank you!' );

break statement:

break statement is used to end or terminate the loop.

Sample Code:

strNumber = input(
    'Please Enter a Number: '
);
intNumber = int( strNumber );
while intNumber > 0 :
    print( intNumber );
    intNumber = intNumber - 1;
    strInput = input(
        'Do you want to close this loop? Enter Y/N: '
    );
    if strInput == 'Y' :
        print( 'Closing the loop' );
        break;
print( 'Thank you!' );

for loop:

for loop is used to iterate or repeat executing the same block of code with a known number of times.

Sample Code:

print( 'Before For Loop' );
for i in [ 1, 2, 3, 4, 5 ] :
    print ( i );
print( 'After For Loop' );

Leave a Reply