4) Loops

For Repeating code many numbers of time we use loops

While Loop:

While loops execute a block of code until a block of code evaluates to true

x= x+1

if __name__ == ‘__main__’:
main()

0
1
2
3
4

For loop

Output
1
2
3
4
5

    • Python loops work somewhat different from other programming languages
    • We define a range function to 1,6 to which it will iterate
    • Here you note 6 that is the last number is not inclusive of the result. So the end number is not included in the range

Python loops with a list

jan
feb
march
april

Break and continue Statement

1
2
3
4

When a value of x reaches 5 it simply breaks the loop and comes out of the loop.

Continue: skips the rest of the loop for that particular iteration

Output:

1
3
5
7
9

In the example here if x%2 == 0 it will skip the rest part of loop and continue with next value.

Using enumerate() function

We can use the enumerate() function to get index

Noramally for loop in python does not have key index value like any other programming language. But if we need key value pair we can use enumerate function

Output:
(0, ‘jan’)
(1, ‘feb’)
(2, ‘march’)
(3, ‘april’)

This function will return the index and value pair