1 / 28

Looping

Looping. for. for loop. The for loop in Python is more like a foreach iterative-type loop in a shell scripting language than a traditional for conditional loop that works like a counter. Python's for takes an iterable (such as a sequence or iterator) and traverses each element once.

tavi
Download Presentation

Looping

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

  2. for loop • The for loop in Python is more like a foreach iterative-type loop in a shell scripting language than a traditional for conditional loop that works like a counter. • Python's for takes an iterable (such as a sequence or iterator) and traverses each element once. • Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.

  3. General Syntax for iter_var in iterable: suite_to_repeat • The for loop traverses through individual elements of an iterable (like a sequence or iterator) and • terminates when all the items are exhausted.

  4. Example 1 >>> print 'I like to use the Internet for:' I like to use the Internet for: >>> for item in ['e-mail', 'net-surfing', 'homework', 'chat']: ... print item ... e-mail net-surfing homework chat

  5. continue • how we can make Python's for statement act more like a traditional loop, in other words, a numerical counting loop ????? • The behavior of a for loop (iterates over a sequence) cannot be change, thus to make it like traditional loop , manipulate the sequence so that it is a list of numbers • “iterating over a sequence”

  6. Example-c language #include<stdio.h> int main() { inti; for (i = 0; i < 10; i++) { printf ("Hello\n"); printf ("World\n"); } return 0; } Work like counter Python is not working like this!!!!!

  7. Used with Sequence Types • Examples - string, list, and tuple types >>> for each Letter in 'Names': ... print 'current letter:', each Letter ... current letter: N current letter: a current letter: m current letter: e current letter: s

  8. Using for in string • For strings, it is easy to iterate over each character: >>> foo = 'abc' >>> for c in foo: ... print c ... a b c

  9. continue • When iterating over a string, the iteration variable will always consist of only single characters (strings of length 1). • When seeking characters in a string, more often than not, the programmer will either use in to test for membership, or one of the string module functions or string methods to check for sub strings.

  10. continue • iterating through each item is by index offset into the sequence itself: >>> nameList = ['Cathy', "Terry", 'Joe', 'Heather', 'Lucy'] >>> for nameIndex in range(len(nameList)): ... print "Liu,", nameList[nameIndex] ... Liu, Cathy Liu, Terry Liu, Joe Liu, Heather Liu, Lucy

  11. continue • employ the assistance of the len() built-in function, which provides the total number of elements in the tuple • as well as the range() built-in function to give us the actual sequence to iterate over. >>> len(nameList) 5 >>> range(len(nameList)) [0, 1, 2, 3, 4]

  12. continue • Since the range of numbers may differ, Python provides the range() built-in function to generate such a list. • It does exactly what we want, taking a range of numbers and generating a list.

  13. continue • To iterate over the indices of a sequence, combine range() and len() as follows: >>> a = [’Mary’, ’had’, ’a’, ’little’, ’lamb’] >>> for i in range(len(a)): ... print i, a[i] ... 0 Mary 1 had 2 a 3 little 4 lamb

  14. Example : using range and numerical operator Without this!!!!!! >>> for eachnum in range(10): ... eachnum=eachnum+2 ... print eachnum ... 2 3 4 5 6 7 8 9 10 11 0 1 2 3 4 5 6 7 8 9

  15. range () and len() >>> foo = 'abc' >>> for i in range(len(foo)): ... print foo[i], '(%d)' % i ... a (0) b (1) c (2) index element

  16. Iterating with Item and Index • When looping through a sequence, the position index and corresponding value can be retrieved at the same time • using the enumerate() function. >>> for i, v in enumerate([’tic’, ’tac’, ’toe’]): ... print i, v ... 0 tic 1 tac 2 toe

  17. continue >>> nameList = ['Donn', 'Shirley', 'Ben', 'Janice‘, 'David', 'Yen', 'Wendy'] >>> for i, eachLee in enumerate(nameList): ... print "%d %s Lee" % (i+1, eachLee) ... 1 Donn Lee 2 Shirley Lee 3 Ben Lee 4 Janice Lee 5 David Lee 6 Yen Lee 7 Wendy Lee When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function. >>> for i, v in enumerate([’tic’, ’tac’, ’toe’]): ... print i, v ... 0 tic 1 tac 2 toe

  18. Example 2 print 'I like to use the Internet for:' for item in ['e-mail', 'net-surfing', 'homework', 'chat']: print item, print • put comma to display the items on the same line rather than on separate lines • Put one print statement with no arguments to flush our line of output with a terminating NEWLINE • by default print statement automatically created newline like example 1

  19. Continue.. • Output: I like to use the Internet for: e-mail net-surfing homework chat • Elements in print statements separated by commas will automatically include a delimiting space between them as they are displayed.

  20. example >>> for eachNum in [0, 1, 2]: ... print eachNum ... 0 1 2 ***Within the loop, eachNum contains the integer value that we are displaying and can use it in any numerical calculation that user wish***

  21. example >>> for eachNum in range(3): ... print eachNum ... 0 1 2 >>> for eachnum in range(6): ... print eachnum ... 0 1 2 3 4 5

  22. >>> for a in range (3): ... a= a*2 ... print a ... 0 2 4

  23. List Comprehensions >>> squared = [x ** 2 for x in range(4)] >>> for i in squared: ... print i 0 1 4 9

  24. continue >>> sqdEvens = [x ** 2 for x in range(8) if not x % 2] >>> >>> for i in sqdEvens: ... print i 0 4 16 36

  25. continue • To loop over two or more sequences at the same time, the entries can be paired with the zip() function. >>> questions = [’name’, ’quest’, ’favorite color’] >>> answers = [’lancelot’, ’the holy grail’, ’blue’] >>> for q, a in zip(questions, answers): ... print ’What is your %s? It is %s.’ % (q, a) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue.

  26. Use for to read data in file filename = raw_input('Enter file name: ') fobj = open(filename, 'r') for eachLine in fobj: print eachLine, fobj.close()

  27. break and continue Statements, and else Clauses on Loops • The break statement, like in C, breaks out of the smallest enclosing for or while loop. • The continue statement, also borrowed from C, continues with the next iteration of the loop. • Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. • This is exemplified by the following loop, which searches for prime numbers:

  28. 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 example >>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print n, ’equals’, x, ’*’, n/x ... break ... else: ... # loop fell through without finding a factor ... print n, ’is a prime number’ ...

More Related