Computers are often used to automate repetitive tasks. Repeating identical or
similar tasks without making errors is something that computers do well and people
do poorly. Because iteration is so common, Python provides several language
features to make it easier.
A loop statement allows us to execute a statement or group of statements multiple times.
While Loop Statements
One form of iteration in Python is the while statement.
A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.
Here is syntax
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements with uniform indent. The condition may be any expression, and true is any non-zero value.
The loop iterates while the condition is true.When the condition becomes false, program control passes to the line immediately following the loop.
for example :-
You can almost read the while statement as if it were English. It means, “While
n is greater than 0, display the value of n and then reduce the value of n by 1.
When you get to 0, exit the while statement and display the word Blastoff!”
More formally, here is the flow of execution for a while statement:
1. Evaluate the condition, yielding True or False.
2. If the condition is false, exit the while statement and continue execution at
the next statement.
3. If the condition is true, execute the body and then go back to step 1.
This type of flow is called a loop because the third step loops back around to the
top. We call each time we execute the body of the loop an iteration. For the above
loop, we would say, “It had five iterations”, which means that the body of the loop
was executed five times.
The body of the loop should change the value of one or more variables so that
eventually the condition becomes false and the loop terminates. We call the vari-
able that changes each time the loop executes and controls when the loop finishes
the iteration variable. If there is no iteration variable, the loop will repeat forever,resulting in an infinite loop.
The Infinite Loop
A loop becomes infinite loop if a condition never becomes FALSE. You must be cautious
when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop
For Loop Statements
Sometimes we want to loop through a set of things such as a list of words, the lines
in a file, or a list of numbers. When we have a list of things to loop through, we
can construct a definite loop using a for statement. We call the while statement
an indefinite loop because it simply loops until some condition becomes False,
whereas the for loop is looping through a known set of items so it runs through
as many iterations as there are items in the set.
The syntax of a for loop is similar to the while loop in that there is a for
statement and a loop body:
Syntax
for iterating_var in sequence:
statements(s)
for example :
Translating this for loop to English is not as direct as the while, but if you think
of friends as a set, it goes like this: “Run the statements in the body of the for
loop once for each friend in the set named friends.”
Looking at the for loop, for and in are reserved Python keywords, and friend
and friends are variables.
In particular, friend is the iteration variable for the for loop. The variable friend
changes for each iteration of the loop and controls when the for loop completes.
The iteration variable steps successively through the three strings stored in the
friends variable.
Nested Loops
Python programming language allows the use of one loop inside another loop. The
following section shows a few examples to illustrate the concept.
Syntax : -
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is as follows :-
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example a for loop can be inside a while loop or vice versa.
The print() function inner loop has end=' ' which appends a space instead of default
newline. Hence, the numbers will appear in one row.
Last print() will be executed at the end of inner for loop.
Loop Control Statements
The Loop control statements change the execution from its normal sequence. When the execution leaves a scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements.
Statement | Description |
---|---|
break | Terminates the loop statement and transfers execution to the statement immediately following the loop. |
continue | Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. |
pass | The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. |
<table> pass, break, continue<table>
break statement
The break statement is used for premature termination of the current loop. After
abandoning the loop, execution at the next statement is resumed.
The most common use of break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.
If you are using nested loops, the break statement stops the execution of the innermost loop and starts executing the next line of the code after the block.
Syntax
The syntax for a break statement in Python is as follows-
break
For example, suppose you want to take input from the user until they type done.
You could write:
The loop condition is True, which is always true, so the loop runs repeatedly until
it hits the break statement.
Each time through, it prompts the user with an angle bracket. If the user types
done, the break statement exits the loop. Otherwise the program echoes whatever
the user types and goes back to the top of the loop. Here’s a sample run:
This way of writing while loops is common because you can check the condition
anywhere in the loop (not just at the top) and you can express the stop condition
affirmatively (“stop when this happens”) rather than negatively (“keep going until
that happens.”).
continue Statement
The continue statement in Python returns the control to the beginning of the current loop.
When encountered, the loop starts next iteration without executing the remaining
statements in the current iteration.
The continue statement can be used in both while and for loops.
Syntax :-
continue
Sometimes you are in an iteration of a loop and want to finish the current iteration
and immediately jump to the next iteration. In that case you can use the continue
statement to skip to the next iteration without finishing the body of the loop for
the current iteration.
Here is an example of a loop that copies its input until the user types “done”, but
treats lines that start with the hash character as lines not to be printed (kind of
like Python comments.
All the lines are printed except the one that starts with the star sign because
when the continue is executed, it ends the current iteration and jumps back to
the while statement to start the next iteration, thus skipping the print statement.
0 Comments