step1:while you are here
The while loop is similar to an if statement: it executes the code inside of it if some condition is true.
The difference is that the while loop will continue to execute as long as the condition is true. In other words, instead of executing if something is true, it executes while that thing is true.
count = 0
if count < 5:
print "Hello, I am an if statement and count is", count
while count < 10:
print "Hello, I am a while and count is", count
count += 1
step2:Condition
The condition is the expression that decides whether the loop is going to be executed or not. There are 5 steps to this program:
1.The loop_condition variable is set toTrue
2. The while loop checks to see if loop_condition isTrue. It is, so the loop is entered.
3. The print statement is executed.
4.The variable loop_condition is set to False.
5.The while loop again checks to see if loop_condition is True. It is not, so the loop is not executed a second time.
loop_condition = True
while loop_condition:
print "I am a loop"
loop_condition = False
step3:While you're at it
Inside a while loop, you can do anything you could do elsewhere, including arithmetic operations.
num = 1
while num<=10: # Fill in the condition
print num**2 # Print num squared
num+=1 # Increment num (make sure to do this!)
step4:Simple errors
A common application of awhileloop is to check user input to see if it is valid. For example, if you ask the user to enteryornand they instead enter7, then you should re-prompt them for input.
choice = raw_input('Enjoying the course? (y/n)')
while (choice!='y' and choice!='n'): # Fill in the condition (before the colon)
choice = raw_input("Sorry, I didn't catch that. Enter again: ")
step5:Infinite loops
Aninfinite loopis a loop that never exits. This can happen for a few reasons:
The loop condition cannot possibly be false (e.g.while1!=2)
The logic of the loop prevents the loop condition from becoming false.
Example:
count =10
while count >0:
count +=1# Instead of count -= 1
count = 0
while count < 10: # Add a colon
print count
count+=1# Increment count
step6:Break
The break is a one-line statement that means "exit the current loop." An alternate way to make our counting loop exit and stop executing is with thebreakstatement.
First, create awhilewith a condition that is always true. The simplest way is shown.
Using anifstatement, you define the stopping condition. Inside theif, you writebreak, meaning "exit the loop."
The difference here is that this loop is guaranteed to run at least once.
count = 0
while True:
print count
count += 1
if count >= 10:
break
step7:While / else
Something completely different about Python is thewhile/elseconstruction.while/elseis similar toif/else, but thereisa difference: theelseblock will executeanytimethe loop condition is evaluated toFalse. This means that it will execute if the loop is never entered or if the loop exits normally. If the loop exits as the result of abreak, theelsewill not be executed.
In this example, the loop willbreakif a 5 is generated, and theelsewill not execute. Otherwise, after 3 numbers are generated, the loop condition will become false and the else will execute.
import random
print "Lucky Numbers! 3 numbers will be generated."
print "If one of them is a '5', you lose!"
count = 0
while count < 3:
num = random.randint(1, 6)
print num
if num == 5:
print "Sorry, you lose!"
break
count += 1
else:
print "You win!"
step8:Your own while / else
Now you should be able to make a game similar to the one in the last exercise. The code from the last exercise is below:
count =0
while count <3:
num = random.randint(1,6)
print num
if num ==5:
print"Sorry, you lose!"
break
count +=1
else:print"You win!"
In this exercise, allow the user to guess what the number isthreetimes.
guess = int(raw_input("Your guess: "))
Remember,raw_inputturns user input into a string, so we useint()to make it a number again.
from random import randint
# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)
guesses_left = 3
# Start your game!
while guesses_left>0:
guess = int(raw_input("Your guess: "))
if(guess==random_number):
print "You win!"
break
guesses_left-=1
else:
print "You lose"
step9:For your health
An alternative way to loop is theforloop. The syntax is as shown; this example means "for each numberiin the range 0 - 9, printi".
print "Counting..."
for i in range(20):
print i
step10:For your hobbies
This kind of loop is useful when you want to do something a certain number of times, such as append something to the end of a list.
hobbies = []
for i in range(3):
guess = raw_input("Your hobby: ")
hobbies.append('guess')# Add your code below!
step11:For your strings
Using aforloop, you can print out each individual character in a string.
The example in the editor is almost plain English: "for each charactercinthing, printc".
Instructions
thing = "spam!"
for c in thing:
print c
word = "eggs!"
# Your code here!
for d in word:
print d
step12:For your A
String manipulation is useful inforloops if you want to modify some content in a string.
word ="Marble"forcharinword:printchar,
The example above iterates through each character inwordand, in the end, prints outM a r b l e.
The,character after ourprintstatement means that our nextprintstatement keeps printing on the same line.
phrase = "A bird in the hand..."
# Add your for loop
for char in phrase:
if char=='A' or char=='a':
print 'X',
else:
print char,
#Don't delete this print statement!
print 语句后面加逗号,是为了将输出显示为同一行
step13:For your lists
Perhaps the most useful (and most common) use offorloops is to go through a list.
On each iteration, the variablenumwill be the next value in the list. So, the first time through, it will be7, the second time it will be9, then12,54,99, and then the loop will exit when there are no more values in the list.
numbers = [7, 9, 12, 54, 99]
print "This list contains: "
for num in numbers:
print num
# Add your loop below!
for num in numbers:
print num**2
step14:Looping over a dictionary
You may be wondering how looping over a dictionary would work. Would you get the key or the value?
The short answer is: you get the key which you can use to get the value.
d = {'x':9,'y':10,'z':20}
for key in d:
if d[key] ==10:
print"This dictionary has the value 10!"
First, we create a dictionary with strings as the keys and numbers as the values.
Then, we iterate through the dictionary, each time storing the key inkey.
Next, we check if that key's value is equal to 10.
Finally, we printThisdictionary has the value10!
d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}
for key in d:
# Your code here!
print key+' '+d[key]
step15:Counting as you go
A weakness of using this for-each style of iteration is that you don't know the index of the thing you're looking at. Generally this isn't an issue, but at times it is useful to know how far into the list you are. Thankfully the built-inenumeratefunction helps with this.
enumerateworks by supplying a corresponding index to each element in the list that you pass it. Each time you go through the loop,indexwill be one greater, anditemwill be the next item in the sequence. It's very similar to using a normalforloop with a list, except this gives us an easy way to count how many items we've seen so far.
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
print index+1, item
step16:Multiple lists
It's also common to need to iterate over two lists at once. This is where the built-inzipfunction comes in handy.
zipwill create pairs of elements when passed two lists, and will stop at the end of the shorter list.
zipcan handle three or more lists as well!
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_a, list_b):
# Add your code here!
if(a>b):
print a
else:
print b
step17:For / else
Just like withwhile,forloops may have anelseassociated with them.
In this case, theelsestatement is executed after thefor, butonlyif theforends normally—that is, not with abreak. This code willbreakwhen it hits'tomato', so theelseblock won't be executed.
fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']
print 'You have...'
for f in fruits:
if f == 'tomato':
print 'A tomato is not a fruit!' # (It actually is.)
break
print 'A', f
else:
print 'A fine selection of fruits!'
step18:Change it up
As mentioned, theelseblock won't run in this case, sincebreakexecutes when it hits'tomato'.
fruits = ['banana', 'apple', 'orange', 'peach', 'pear', 'grape']
print 'You have...'
for f in fruits:
if f == 'tomato':
print 'A tomato is not a fruit!' # (It actually is.)
break
print 'A', f
else:
print 'A fine selection of fruits!'