What are the Loops?
A loop statement allows us to execute a statement or group of statements multiple times.
The following diagram illustrates a loop statement.
While loop--
- Repeats a statement or group of statements while a given condition is TRUE.
- It tests the condition before executing the loop body.
While Loop Statements:
Syntax:
Below is the syntax of while loop.
- while expression: ( expression end with semicolon)
- statement(s)
- 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.
Example
#!/usr/bin/python3
count
= 1
while
(count < 10):
print
('The count is:', count)
count
= count + 1
print
("move on!")
When the above code is executed, it produces the following result-
The
count is: 1
The
count is: 2
The
count is: 3
The
count is: 4
The
count is: 5
The
count is: 6
The
count is: 7
The
count is: 8
The
count is: 9
move on!
The block
here, consisting of the print and increment statements, is executed repeatedly
until
count is no longer less than 10. With each iteration, the current value of the
index is increased by 1.
The Infinite Loop:
- A loop become infinite loop if the given condition become always true till infinite times.
- While creating a loop you should be cautious enough as there might be possibility when a condition never false and result the infinite loop.
- An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required.
while True:
num = int(input("Enter an integer:
"))
print("The square of",num,"is",num**2)
Using else Statement in
while Loop:
· If the else statement
is used with a while loop, the
else statement
is executed
when the
condition becomes false.
- The following example illustrates the combination of an else statement with a while
statement
that prints a number as long as it is less than 6, otherwise the else statement
gets
executed.
#!/usr/bin/python3
count
= 0
while
count < 6:
print
(count, " is less than 6")
count
= count + 1
else:
print
(count, " is not less than 6")
When the above code is executed, it produces the following result-
0
is less than 5
1
is less than 5
2
is less than 5
3
is less than 5
4
is less than 5
5
is less than 6
6
is not less than 5
Read More: Python Doc
No comments:
Post a Comment