Top Banner
for
28

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.

Jan 02, 2016

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 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.

for

Page 2: 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.

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

Page 3: 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.

General Syntaxfor 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.

Page 4: 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.

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-mailnet-surfinghomeworkchat

Page 5: 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.

continuehow 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”

Page 6: 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.

Example-c language#include<stdio.h> int main() { int i; for (i = 0; i < 10; i++) { printf ("Hello\n"); printf ("World\n"); } return 0; }

Work like counter

Python is not working like this!!!!!

Page 7: 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.

Used with Sequence TypesExamples - string, list, and tuple types

>>> for each Letter in 'Names':... print 'current letter:', each Letter...current letter: Ncurrent letter: acurrent letter: mcurrent letter: ecurrent letter: s

Page 8: 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.

Using for in stringFor strings, it is easy to iterate over each

character:>>> foo = 'abc'>>> for c in foo:... print c...abc

Page 9: 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.

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

Page 10: 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.

continueiterating 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, CathyLiu, TerryLiu, JoeLiu, HeatherLiu, Lucy

Page 11: 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.

continueemploy 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]

Page 12: 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.

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

Page 13: 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.

continueTo 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 Mary1 had2 a3 little4 lamb

Page 14: 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.

Example : using range and numerical operator >>> for eachnum in range(10):... eachnum=eachnum+2... print eachnum...234567891011

0123456789

Without this!!!!!!

Page 15: 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.

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

index

element

Page 16: 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.

Iterating with Item and IndexWhen 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 tic1 tac2 toe

Page 17: 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.

continue>>> nameList = ['Donn', 'Shirley', 'Ben', 'Janice‘, 'David', 'Yen',

'Wendy']>>> for i, eachLee in enumerate(nameList):... print "%d %s Lee" % (i+1, eachLee)...

1 Donn Lee2 Shirley Lee3 Ben Lee4 Janice Lee5 David Lee6 Yen Lee7 Wendy Lee

When looping through a sequence, the position index and corresponding value can be retrieved at the same timeusing the enumerate() function.>>> for i, v in enumerate([’tic’, ’tac’, ’toe’]):... print i, v...0 tic1 tac2 toe

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

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

Page 19: 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.

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.

Page 20: 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.

example>>> for eachNum in [0, 1, 2]:... print eachNum...012 ***Within the loop, eachNum contains the

integer value that we are displaying and can use it in any numerical calculation that user wish***

Page 21: 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.

example>>> for eachNum in range(3):... print eachNum...012

>>> for eachnum in range(6):... print eachnum...012345

Page 22: 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.

>>> for a in range (3):... a= a*2... print a...024

Page 23: 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.

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

Page 24: 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.

continue>>> sqdEvens = [x ** 2 for x in range(8) if

not x % 2]>>>>>> for i in sqdEvens:... print i041636

Page 25: 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.

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

Page 26: 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.

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

Page 27: 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.

break and continue Statements, and else Clauses on LoopsThe 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:

Page 28: 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.

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

2 is a prime number3 is a prime number4 equals 2 * 25 is a prime number6 equals 2 * 37 is a prime number8 equals 2 * 49 equals 3 * 3