Sunday, September 12, 2010

The While Loop in Python

The while loop says that while one thing is true, do something. Here we can count to ten:

counter=0
while counter < 11:
 print(counter)
 counter=counter+1

What did we do here? First we initilized counter as 0, this is where our counter is starting. It is important to initialize the variable you are using in your while loop outside of the loop. After we have initialized counter to 0 we say: While the value of counter is less than 11, do something. In our case, do something is print(counter), which the first time through would be 0, and then we set counter equal to itself plus one.

Our loop will now continue with counter as 1 print one and add 1 to itself. When counter is equal to 10, it goes through one last time, prints 10 adds one to 11 and then passes through the while test again. This time it is not less than 11, because it equals 11 and so it stops. Your output should be:

0
1
2
3
4
5
6
7
8
9
10

We can say this same thing but, in my opinion, make it look nicer. We can do this by making use of multiple operators. The first example will be in line 2, instead of < 11, we can use <=10, which is less than or equal to. A list of such comparison operators is:

<=     If left operand is less than or equal to right operand, condition is true.
>=     If left operand is greater than or equal to right operand, condition is true
==     If left operand is equal to right operand, condition is true.
!=      If left operand is not equal to right operand, condition is true.

Notice the difference between the assignment operator = and the conditional operator ==. The first makes one operand equal another, the other tests the equality of the two operands. 

The second way we can simplify the program is by using the compound assignment operator +=. In line 4, where we say counter=counter+1, the same thing could be said with the expression, counter+=1. This takes the value of counter, adds one and assigns that value to counter. You can see how this be of use. Here are some more compound assignment operators:

+=  Adds left and right operand and assigns total to left operand
-= Subracts right from left operand and assigns total to left operand

*=Multiplies left and right operand and assigns total to left operand
/= Divides right from left operand and assigns total to left operand
**= Takes left operand to the power of the right operand and assigns total to left operand
%= Finds remainder of division between left operand and right operand, and assigns total to left operand.
//= Performs integer division between left and right operand and assigns total to left operand.

Our "improved" code would now be:


counter=0
while counter <= 10:
 print(counter)
 counter+=1

No comments:

Post a Comment