Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 10 Loops: while and for CSC1310 Fall 2009.

Similar presentations


Presentation on theme: "Chapter 10 Loops: while and for CSC1310 Fall 2009."— Presentation transcript:

1 Chapter 10 Loops: while and for CSC1310 Fall 2009

2 Loop looping repeat Python has two main looping constructs --- statements that repeat an action over and over while The while loop provides a way to code general loop. for 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 : #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.

4 while in Action Be careful with. >>>while 1: print “I will run forever!\n” (infinite loop) Python will execute it for ever since is always true (infinite loop). Ctrl-C 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 break jumps out of the closest enclosing loop (past the entire loop statement) continue jumps to the top continue jumps to the top of the closest enclosing loop (to the loop’s header line) while : #start of body #start of body if :break if :break if : continue if : continue #end of body #end of body else: #runs only if loop is exited normally

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 iterator. The for loop is a generic sequence iterator. ANY ordered It can step through the items in ANY ordered sequence object General format: for in : else: 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. automatically It is automatically set to the next item in sequence when control returns to the top of the loop again. break After the loop, this variable normally still refers to the last item visited unless loop exits with break. for in : #start of body #start of body if :break if :break if : continue if : continue #end of body #end of body else: #runs only if loop is exited normally

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? while You could use while with manual indexing. range for (xrange). 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()for 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 Tuples 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 sequence Immutable sequence Fixed length, heterogeneous, arbitrary nestable Fixed length, heterogeneous, arbitrary nestable Arrays of object references Arrays 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 >>>t5=(‘0’, (‘abc’, ‘345’))

20 Basic operations: len(), +, *,in len(t1)t1. len(t1) returns number of items in the tuple t1. >>>len((1, 2, (4,5))) t1+t2 (concatenation)t1 t2 t1+t2 (concatenation) creates a new tuple by joining t1 and t2. >>>(1, 2, 3) + (‘a’, ’b’, ’c’) t1*i (repeat)t1i t1*i (repeat) adds t1 to itself i times. >>> (1, 2)*3 obj1 in t1 (membership)obj1 t1 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 list() To sort tuple, convert it to list with list() >>>t=(‘cc’, ’bb’, ’aa’, ’dd’, ‘ee’) >>>tmp=list(t) >>>tmp.sort() >>>print tmp l1tuple(l1) 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()for zip() allows to use for to visit multiple sequences in parallel. sequences of any type list of tuples 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 truncates shortest sequence zip() truncates result tuples at the length of the shortest sequence >>>zip(‘abcdef’, (1,), [2,3,4,5]) map() None 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 dict() Object-construction request with dict() >>>D3=dict(zip(keys,vals))


Download ppt "Chapter 10 Loops: while and for CSC1310 Fall 2009."

Similar presentations


Ads by Google