Py-Tut-006

Back to Learning Python



Loops
A Loop is a segment of code that repeats itself until a condition is satisfied. Most often the condition has a "counter" which is simply a variable often used to count iterations. Note that the counter variable does not need to be in the condition being tested.

While
The While loop will first test a condition and then continually repeat the indented code until the condition is satisfied.

code format="python" counter = 0 while x < 100: x = x * 2 counter = counter + 1

print x, counter code



Notice for our above example that x was 128 and the counter looped 7 times.

The "for" Statement
The While loop above is very useful but what if you just want to loop through each item of a list? This is where the "for" statement comes in handy.

Let's say you had a list of the months and wanted to print each one.

code format="python" months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

for i in months: print i

code

The Case Statement
From Monty Python and the Holy Grail:

French Soldier: Un cadeau. Other French soldiers: A what? French Soldier: A present. Other French soldiers: Oh. Un cadeau. Other French soldiers: Oui oui. French Soldier: Allons y! Other French soldiers: What? French Soldier: Let's go! Other French soldiers: Oh.

A Gift you say? What kind of gift? There is no Case statement in Python so you will not have to deal with it for now. You may view the following links for the official reason there is no Case statement as well as links to building your own alternatives here:
 * []
 * []
 * []

Assignment 6a
Pick a number between one and ten. Use a while loop to ask a user to guess your number. Continue the loop until the user guesses the number correctly.

Assignment 6b
Modify Assignment 4 so that it uses a "for" statement.

Back to Learning Python