WhirlwindTourOfPython repository or copy the Scripts files to your local workspaceplayerCount'= {'Volleyball': 6, 'Baseball': 9}x = playerCount['Volleyball']playerCount['Volleyball'] = 2playerCount['Soccer'] = 11See Getting-Started-with-PythonWin.html
for loopsfor x in myList: for is available in the code block and changes with each iteration of the looprange() function to create a simple list to loop a set number of times
In [ ]:
#ForLoopExample.py
# This example uses a for loop to iterate through each item in
# the "fruit" list, updating the value of the "fruit" variable and
# executing whatever lines are indented under the for statement
#Create a list of fruit
fruitList = ("apples","oranges","kiwi","grapes","blueberries")
# Loop through each item in the tuple and execute
# each line that is indented under the for loop
for fruit in fruitList:
print "I like to eat " + fruit
# Dedented lines are run after the loop completes
print "\nI like ice cream too..."
In [ ]:
print range(10)
In [ ]:
print range(10,100)
In [ ]:
print range(10,100,20)
In [ ]:
#RangeFunctionExample.py
# This example demonstrates the range function for generating
# a sequence of values that can be used in a for loop.
pi = 3.1415
for r in range(0,100,20):
area = (r ** 2) * pi
print "The area of a circle with radius ", r, "is ", area
In [ ]:
#WhileLoopExample.py
# This example demonstrates how a while loop is used. Here, we
# calculate the area of several circle with a radius 'r'. We loop
# through gradually larger values of r until the area of the circle
# exceeds 1000.
pi = 3.1415
r = 1
area = (r ** 2) * pi
while area < 1000:
print r, area # Indentation indicates what's run in the loop
r = r + 1 # The variable that gets evaluated must change in the
area = (r ** 2) * pi # loop otherwise you'll create an infinite loop!
print "The while loop is done" # Dedented lines run after the loop completes