1 / 24

Chapter 10 Loops: while and for

Chapter 10 Loops: while and for. CSC1310 Fall 2009. Loop. Python has two main looping constructs --- statements that repeat an action over and over The while loop provides a way to code general loop.

fedella
Download Presentation

Chapter 10 Loops: while and for

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 10 Loops: while and for CSC1310 Fall 2009

  2. Loop • Python has two main looping constructs --- statements that repeat an action over and over • The while loop provides a way to code general loop. • The for statement steps through the items in a sequence object and runs a block of code for each of them.

  3. While Loop • General format: while <test expression>: <statement1> #start of body <statement2> <statement3> #end of body else: <statements> • It repeatedly executes the body, as long as test expression at the top has true value. • 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.

  4. while 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). • Ctrl-C stops execution.

  5. “while” in Action • Prints all odd numbers between 0 and 10 >>>count=0 >>>while count<=10: if count%2!=0: print count count+=1 # count=count+1 else: print “Done” • Iterates through string >>>x=‘while’ >>>while x: print x #print x, - what has changed? x=x[1:]

  6. How to Get Such Output?

  7. break and continue • breakjumps out of the closest enclosing loop (past the entire loop statement) • continue jumps to the top of the closest enclosing loop (to the loop’s header line) while <test1>: <statements> #start of body if <test2>:break if <test3>: continue <statements> #end of body else: #runs only if loop is exited normally <statements>

  8. continue 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”

  9. break 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)

  10. break 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

  11. for Loop • The for loop is a generic sequence iterator. • It can step through the items in ANYorderedsequence object • General format: for <target> in <object>: <statements> else: <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.

  12. for Loop • The name for the target is usually a (new) variable. • It is automatically 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 break. for <target> in <object>: <statements> #start of body if <test1>:break if <test2>: continue <statements> #end of body else: #runs only if loop is exited normally <statements>

  13. for 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”

  14. for 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

  15. Loop 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 while with manual indexing. • Or built-in range function to produce list of successively higher integers that could be used as indices in for (xrange).

  16. Counter Loops: range • range() is independent from for loop. >>>range(5), range(-2,3), range(2,11,3),range(2,-3,-1) >>>i=1 >>>while i<10: print i i+=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]

  17. Nonexhaustive Traversals: 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

  18. 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

  19. New Type: Tuples • Tuples are collections of any objects that can not be changed. • Ordered collection of arbitrary objects • Accessed by offset (indexing, slicing) • Immutable sequence • Fixed length, heterogeneous, arbitrary nestable • Arrays of object references >>>t1=() # an empty list >>>t2=(0,) # not an expression >>>t3=(0, ’Ni’, 1.3, 4); t4=0, ’Ni’, 1.3, 4 >>>t5=(‘0’, (‘abc’, ‘345’))

  20. Basic operations: len(), +, *,in • len(t1) returns number of items in the tuple t1. >>>len((1, 2, (4,5))) • t1+t2 (concatenation) creates a new tuple by joining t1 and t2. >>>(1, 2, 3) + (‘a’, ’b’, ’c’) • t1*i (repeat) adds t1 to itself i times. >>> (1, 2)*3 • obj1 in t1 (membership) returns true if obj1 is item of the tuple t1; otherwise, returns false. >>>’a’ in (1,2,’a’) >>>for x in (1, ‘abcd’, (3,4), [4,5, ‘y’]): print x,

  21. Indexing 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’

  22. Tuples and Lists • To sort tuple, convert it to list with list() >>>t=(‘cc’, ’bb’, ’aa’, ’dd’, ‘ee’) >>>tmp=list(t) >>>tmp.sort() >>>print tmp • List l1 to tuple: 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.)

  23. Parallel Traversals: zip and map • zip() allows to use for to visit multiple sequences in parallel. • It takes one or more sequences of any type, and returns a list 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() truncates result tuples at the length of the shortest sequence >>>zip(‘abcdef’, (1,), [2,3,4,5]) • map() does the same as zip(), but pads shorter sequence with None if argument lengths differ. >>>map(None,‘abcdef’, (1,), [2,3,4,5])

  24. Dictionary Construction: zip >>>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() >>>D3=dict(zip(keys,vals))

More Related