The While Statement

One of the main advantages of computers is that they can repeat identical or similar tasks without making errors while people do that poorly. Because iteration is so common. Python provides several language features to make it easier.
One form of iteration in Python is while statement. Here is a simple program that counts down from 10 and then says “Takeoff!”
>>>n = 10
>>>while n > 0:
...         print n
…        n = n -1
10
9
8
7
6
5
4
3
2
1
>>>print ‘Takeoff!’
Takeoff!

Meaning of the previous code: While n is greater than 0, display the value of n and then reduce the value of n by 1. When you get 0, exit the while statement and display the word “Takeoff!”
Flow of execution for a while statement:
·         Evaluate the condition, yielding True or False,
·         If the condition is false, exit the while statement and continue execution at the next statement.
·         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. Each time we execute the body of the loop, we call it an iteration. In our loop we had 10 iterations which means that the loop was executed 10 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. Iteration variable is the variable that changes each time the loop executes and controls when the loop finishes. If there is no iteration variable, the loop will repeat forever resulting in an infinite loop. 

Nema komentara:

Objavi komentar