In this tutorial, we shall be looking on loops, their functioning and uses.
Loops are used in the situations when we want to do the same work many times. If you want to print welcome 4 6 times, then you can simply use the print command and write it.
print(“Welcome”) print(“Welcome”) print(“Welcome”) print(“Welcome”) print(“Welcome”) print(“Welcome”)
for i in range(0,6): print(“Welcome”)
It will show the same result that we got with the use of 6 print statements.
Let us look at some of the loops that we can use in Python.
1) For loop, in this loop we execute the statements multiple times or the number of times you will tell it to do. It also increments the loop variable by itself.
but what if you want to write welcome 100 times or 1000 times, using the print statement is not possible. So, we do it in a programmer’s way that is, a smarter way by using loops, we let them work and save our time.
# Prints out the numbers 0,1,2,3,4 for x in range(5): print(x) # Prints out 3,4,5 for x in range(3, 6): print(x) # Prints out 3,5,7 for x in range(3, 8, 2): print(x) Output : 0 1 2 3 4 3 4 5 3 5 7
2) While loop, in this loop the statement will be executed if the given condition is true. Before running the loop, the condition is checked and then the loop is executed. We need to give a statement in order to increment or decrement the loop variable.
# Prints out 0,1,2,3,4 count = 0 while count < 5: print(count) count += 1 # This is the same as count = count + 1 output : 0 1 2 3 4
We can also use both the loops one inside the other, it is called nested loops.
What if we want to stop a loop from executing or we do not want the interpreter to execute a loop.
Let us look how can we do it.
1) Break: the break statement is used when we want a loop to terminate like in case of the while loop, to stop in from running infinite times, we use the break statement to terminate it.
2) Continue: the continue statement is used when we want to check the condition of the loop one more time, it skips the execution of the body and goes back to the condition.
3) Pass: the pass statement is used when we do not want a statement or command to execute. As soon as the interpreter encounters pass, it would not execute the statement.
That is all for this tutorial, hope you are clear with the topic. Try some of the statements by yourself and see the results. See you in the next one!
Example: # Prints out 0,1,2,3,4
count = 0 while True: print(count) count += 1 if count >= 5: break # Prints out only odd numbers - 1,3,5,7,9 for x in range(10): # Check if x is even if x % 2 == 0: continue print(x) Output : 0 1 2 3 4 1 3 5 7 9