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
1 2 3 4 5 |
def main(): x = 0 # define a while loop while(x<5): print(x) |
1 2 3 |
for x in range(1,10): if(x%2 == 0):continue print(x) |
x= x+1
if __name__ == ‘__main__’:
main()
0
1
2
3
4
For loop
1 2 3 |
# define a for loop for x in range(1,6): print(x) |
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
1 2 3 |
months = ["jan","feb","march","april"] for m in months: print(m) |
jan
feb
march
april
Break and continue Statement
1 2 3 |
for x in range(1,10): if(x==5):break print(x) |
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
1 2 3 |
for x in range(1,10): if(x%2 == 0):continue print(x) |
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
1 2 3 |
months = ["jan", "feb", "march", "april"] for i,m in enumerate(months): print(i, m) |
Output:
(0, ‘jan’)
(1, ‘feb’)
(2, ‘march’)
(3, ‘april’)
This function will return the index and value pair