for. for loop the for loop in python is more like a foreach iterative-type loop in a shell scripting...
TRANSCRIPT
for
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.
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.
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
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”
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!!!!!
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
Using for in stringFor strings, it is easy to iterate over each
character:>>> foo = 'abc'>>> for c in foo:... print c...abc
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.
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
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]
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.
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
Example : using range and numerical operator >>> for eachnum in range(10):... eachnum=eachnum+2... print eachnum...234567891011
0123456789
Without this!!!!!!
range () and len() >>> foo = 'abc'>>> for i in range(len(foo)):... print foo[i], '(%d)' % i...a (0)b (1)c (2)
index
element
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
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
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
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.
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***
example>>> for eachNum in range(3):... print eachNum...012
>>> for eachnum in range(6):... print eachnum...012345
>>> for a in range (3):... a= a*2... print a...024
List Comprehensions>>> squared = [x ** 2 for x in range(4)]>>> for i in squared:... print i0149
continue>>> sqdEvens = [x ** 2 for x in range(8) if
not x % 2]>>>>>> for i in sqdEvens:... print i041636
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.
Use for to read data in filefilename = raw_input('Enter file name: ')fobj = open(filename, 'r')for eachLine in fobj: print eachLine,fobj.close()
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:
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