Looping is an essential part of a programming language. If you want to do a task again and again you want to use a loop. Not only the same work. If some tasks have a similar pattern you can use a loop to automate it. In python there are two important types of loops. Those are for loop and while loop. For loops We use a for loop if we want to do something for a per decided number of times
. In above example we have used a range to tell how many times we want to loop. Let's run it . Also we can use for loop with a list. We can do something to each element of a list. Hear we print out every item in the list.
for i in range(0,5): print(i)
You can see there is another string we print called 'The loop is over' . But it will print one time only. This is because it is not under loop's indentation level. When loop has finished it's work the execution will jump to next line. While loops This is another type of loops. While loops check a given condition and if condition is met, it will do a task.
Langs =['python', 'ruby' , 'pearl' , 'C' , 'VB' , 'assembly' , 'php'] for lang in Langs: print('%s is a programming language' % lang) print('The loop is over')
Hear we started with assigning zero to x. Next we check whether x is smaller than 5 or not. If it's true, we say print the value of x. At same time we add 1 to x. Next we can loop something for a infinity number of times if we want.
x = 0 while x < 5: print(x) x = x + 1 print('The loop is over')
This will keep printing while you close the terminal or press Ctrl + c. Because 1 and all non zero values ate treated as true. Also we can combine a loop with if statement like following.
while 1: print('HacksLand')
Hear we have used an extra command called break. It will break the loop. I think now you have a good understanding about loops. Thank for reading. Just leave a comment if you have a succession or an unclear point.
while 1: x = int(input('Enter a number :')) if x == 5 : break