What are loops?
Generally, loops are known as where the starting and ending points are the same and there is a complete path
so that we can travel on that loop as many times as we can
An infinite number of iterations can be done
We can use the concept of loops when we want to repeat a set of codes a certain number of times
let’s see how we can do it and how the loops are useful for us
Firstly there are 2 types of loops in python
In some cases, we want to check the conditions until the condition fails we have to repeat the same process we will need while loop
A loop is a conditional loop that will repeat commands within it as long as a
conditional remains true (Boolean True).
while <logicalExpression> loop-body
For keyword should be given followed by the Variable name followed by in and then the type of sequence ending with a colon :
The loop will be repeated till it reached the end of the sequence given
How While loop works
we can see the syntax for creating the while loop
here the loop-body can contain a single statement or multiple statements or also an empty statement that is a pass statement.
The loop iterates while the logical Expression evaluates to true.
When the expression becomes false, the program control passes to the line after the loop-body
Flowchart of While loop
n1 = int(input("Enter first number :")) n2 = int(input("Enter second number :")) product = 0 S= n1 while S>0: S= S- 1 product= product + n2 print("The product of", n1, "and", n2, "is", product)
Enter first number :8 Enter second number :9 The product of 8 and 9 is 72
Generally, the while loop is used when we don’t know how many times the loop will be executed,
but if we know the termination condition is known to us then the while loop can be used
the while loop is also known as an entry-controlled loop as it has control over an entry in the loop in the form of test conditions.
Jump functions in While loop:
In Python we are having two jump statements – break and continue to be used within loops to jump out
What are jump statements? where can to break and continue?
The break Statement
A break statement skips the rest of the loop and jumps over to the statement following the loop
for the detailed explanation of break, statements CLICK HERE
The Continue Statement
The continue statement skips other loop statements and begins the next loop formation to occur
for the detailed explanation of Continue, statements CLICK HERE