chapter 10 loops: while and for csc1310 fall 2009
DESCRIPTION
While Loop General format: while : #start of body #start of body #end of body #end of bodyelse: true It repeatedly executes the body, as long as test expression at the top has true value. false When the test becomes false, control continues after all statements (body) in the while block. If the test is initially false, the body never runs.TRANSCRIPT
Chapter 10 Chapter 10 Loops: while and forLoops: while and for
CSC1310 Fall 2009CSC1310 Fall 2009
LoopLoop
Python has two main loopinglooping constructs --- statements that repeatrepeat an action over and over
The whilewhile loop provides a way to code general loop.
The forfor statement steps through the items in a sequence object and runs a block of code for each of them.
While LoopWhile Loop General format:while <test expression>:while <test expression>:
<statement1> <statement1> #start of body#start of body <statement2><statement2> <statement3> <statement3> #end of body#end of body else: else: <statements><statements>
It repeatedly executes the body, as long as test expression at the top has truetrue value.
When the test becomes falsefalse, control continues after all statements (body) in the while block. If the test is initially false, the body never runs.
while in Actionwhile in Action
Be careful with <test expression>.
>>>while 1: print “I will run forever!\n”
Python will execute it for ever since <test expression> is always true (infinite loop)(infinite loop).
Ctrl-CCtrl-C stops execution.
““while” in Actionwhile” in Action Prints all odd numbers between 0 and 10>>>count=0>>>while count<=10:
if count%2!=0: print countcount+=1 # count=count+1
else: print “Done”
Iterates through string>>>x=‘while’>>>while x:
print x #print x, - what has changed?
x=x[1:]
How to Get Such Output?How to Get Such Output?
break and continuebreak and continue breakbreak jumps outjumps out of the closest enclosing loop (past the entire
loop statement) continue continue jumps to the topjumps to the top of the closest enclosing loop (to
the loop’s header line)
while <test1>:while <test1>: <statements> <statements> #start of body#start of body
if <test2>:breakif <test2>:break if <test3>: continueif <test3>: continue <statements> <statements> #end of body#end of body else: else: #runs only if loop is exited normally#runs only if loop is exited normally <statements><statements>
continue in Actioncontinue in Action>>>count=0>>>while count<=10:
if count%2!=0: print count
if count%3==0: print “is divisible by 3” else: print “is not divisible by 3”
count+=1 else: print “Done”>>>count=-1>>>while count<10: count+=1
if count%2==0: continue print count
if count%3==0: print “is divisible by 3” else: print “is not divisible by 3” else: print “Done”
break in Actionbreak in Action
>>>while 1: x=raw_input(“Enter integer\n”) if x.isdigit():break print “It is not a valid input!” else: print “It would not be printed ever!”>>>y=int(x)
break in Actionbreak in Action
>>>x=y/2>>>while x>1: if y%x==0: print y,’ has factor ’,x break x-=1 else: print y, “ is prime” y=7 y=8 y=2
for Loopfor Loop The for loop is a generic sequence iterator.iterator. It can step through the items in ANYANY orderedordered sequence
object General format:for <target> in <object>:for <target> in <object>:
<statements> <statements> else: else: <statements><statements>
When Python runs a for loop, it assigns item in the sequence object to the target “one by one” and executes the loop body for each.
For loop body, assignment target refers to the current item in sequence.
for Loopfor Loop The name for the target is usually a (new) variable. It is automaticallyautomatically set to the next item in sequence when
control returns to the top of the loop again. After the loop, this variable normally still refers to the last
item visited unless loop exits with breakbreak. for <target> in <object>:for <target> in <object>:
<statements> <statements> #start of body#start of body if <test1>:breakif <test1>:break if <test2>: continueif <test2>: continue <statements> <statements> #end of body#end of body else: else: #runs only if loop is exited normally#runs only if loop is exited normally <statements><statements>
for in Actionfor in Action>>>aa=[“spam”, “eggs”, “ham”]>>>for i in aa:
print i
>>>x=[12,121,34,56,105,33,45,101,110]>>>count=0>>>for i in x: if i>100:count+=1 if count==3: print “The third number greater than 100 is ”, i break else: print “There is only ”,count,“ numbers>100”
for in Actionfor in Action
>>>x=[1,2,3,4]>>>sum=0>>>for i in x:
sum = sum + i >>>product=1>>>for i in x:
product = product * i >>>print sum,” ”,product
Loop VariationsLoop Variations
There are also situations where you will need to iterate in a more specialized way in the loop operation.
For example, what if you need to visit every second or third item in a list?
You could use whilewhile with manual indexing. Or built-in rangerange function to produce list of
successively higher integers that could be used as indices in for (for (xrangexrange).).
Counter Loops: rangeCounter Loops: range range()range() is independent from forfor loop.>>>range(5), range(-2,3), range(2,11,3),range(2,-3,-1)
>>>i=1>>>while i<10:
print ii+=2
>>>for i in range(1,10,2):print i
>>>x=‘python’; i=0>>>for item in x:print item,>>>while i<len(x):
print x[i],; i+=1>>>for i in range(len(x)): print x[i]
Nonexhaustive Traversals: Nonexhaustive Traversals: range range >>>x= [1,2,3,4,5,6,7,8,9] If we only want to compute the sum of the first 5 scores:>>>sum=0>>>for i in range(5):>>> sum=sum + x[i]
If we only need to sum even scores:>>>sum=0>>>for i in range(0,len(x),2):>>> sum+=x[i]
>>>sum=0>>>for i in x[::2]: sum+=i
Changing List: range Changing List: range >>>x= [1,2,3,4,5,6,7,8,9]>>>for i in range(len(x)): x[i]+=i
>>>i=0>>>while i<len(x): x[i]+=i i+=1
New Type: TuplesNew Type: Tuples TuplesTuples are collections of any objects that can not be
changed. Ordered collection of arbitrary objects Ordered collection of arbitrary objects Accessed by offset Accessed by offset (indexing, slicing) Immutable sequenceImmutable sequence Fixed length, heterogeneous, arbitrary nestableFixed length, heterogeneous, arbitrary nestable Arrays of object referencesArrays of object references>>>t1=() >>>t1=() # an empty list>>>t2=(0>>>t2=(0,,) ) # not an expression>>>t3=(0, ’Ni’, 1.3, 4); t4=0, ’Ni’, 1.3, 4>>>t3=(0, ’Ni’, 1.3, 4); t4=0, ’Ni’, 1.3, 4>>>t5=(‘0’, (‘abc’, ‘345’))>>>t5=(‘0’, (‘abc’, ‘345’))
Basic operations: len(), +, Basic operations: len(), +, *,in*,in len(t1)len(t1) returns number of items in the tuple t1.t1.>>>len((1, 2, (4,5))) t1+t2 (concatenation)t1+t2 (concatenation) creates a new tuple by joining t1t1 and
t2t2.>>>(1, 2, 3) + (‘a’, ’b’, ’c’) t1*i (repeat)t1*i (repeat) adds t1t1 to itself ii times.>>> (1, 2)*3 obj1 in t1 (membership)obj1 in t1 (membership) returns true if obj1obj1 is item of the
tuple t1t1; otherwise, returns false.>>>’a’ in (1,2,’a’)>>>for x in (1, ‘abcd’, (3,4), [4,5, ‘y’]): print x,
Indexing and SlicingIndexing and Slicing Indexing and slicing work the same way as for
strings or lists.>>>tuple=(‘aa’,’bb’,1.2, [3,4], (5, 6, 7))>>>tuple[1], tuple[-1][1], tuple[-2][0]>>>tuple[::-1], tuple[2:] A list inside a tuple could be changed!>>>tuple=(1, [3,4], (5, 6, 7))>>>tuple[1][1]=‘abc’>>>tuple[1]=‘abc’
Tuples and ListsTuples and Lists To sort tuple, convert it to list with list()list()>>>t=(‘cc’, ’bb’, ’aa’, ’dd’, ‘ee’)>>>tmp=list(t)>>>tmp.sort()>>>print tmp List l1l1 to tuple: tuple(l1)tuple(l1)>>>t=tuple(tmp)>>>print t Lists are for ordered collections that might need to be
changed; tuples cover the other cases. Tuples can be used as dictionary keys (lists can not.)
Parallel Traversals: zip and Parallel Traversals: zip and map map zip()zip() allows to use forfor to visit multiple sequences in
parallel. It takes one or more sequences of any typesequences of any type, and
returns a list of tupleslist of tuples that pair up parallel items taken from its argument.
>>>L1=[65,34,56,43]>>>L2=[‘a’, ’b’, ’c’, ’d’]>>>for (x,y) in zip(L1,L2): print y,’ is ’, x zip() truncatestruncates result tuples at the length of the
shortest sequenceshortest sequence>>>zip(‘abcdef’, (1,), [2,3,4,5]) map()map() does the same as zip(), but pads shorter
sequence with NoneNone if argument lengths differ.>>>map(None,‘abcdef’, (1,), [2,3,4,5])
Dictionary Construction: Dictionary Construction: zipzip>>>keys=[65,34,56,43]>>>vals=[‘a’, ’b’, ’c’, ’d’]>>>D2={}>>>for (k,v) in zip(keys,vals): D2[k]=v>>>print D2
Object-construction request with dict()dict()>>>D3=dict(zip(keys,vals))