Watch video presentation and remember to subscribe to our channel;
In this tutorial we will be discussing various types of loops. As we have been discussing in other languages there are various types of loops such while loop, for loop, do while loop, for in loop among others. But in python there are two main loops that are applied they are;
- While loop
- For loop
But in this tutorial we will discuss while loop,
While loop – while loop is applied when one wishes to execute a block of codes repeatedly as long as the condition remains true.
-In this tutorial we will also discuss use of break statement, continue statement and else statement.
For better understanding we may have an example here for better understanding; In this example we will have to add an increment operator to specify the value by which it will be changing with.
x = 1 while x < 8 print(x) x += 1
-In this section we will discuss break statement, else statement and continue statement which are used in various occasions with while loop.
a) Else statement
For instance when the condition in a while loop becomes false then we can still execute the block of codes, let’s look at this example;
x = 1 while x < 8 print(x) x += 1 else: print("The value is greater than 8")
b) Break statement
For instance you may be interested to stop the loop even if the condition is true at a certain value then you will use break statement, let’s have an example here;
x = 1 while x < 8 print(x) if x == 5: break x += 1
c) Continue statement
In this case when we breaks a loop then we use continue statement to continue the statement, first the loops stops at a certain point as specified then it continues, using the example for break statement the loop stops at 5 then it continues. Lets have an example here for better understanding;
x = 1 while x < 8 x += 1 if x == 5: continue print(x)
Thanks for reading through our tutorial, next we will be discussing for loop, just click on next button. Hope you now understand while loop you may try using other example and values.