For
The For statement in Python is slightly different from C or Pascal. The usual loops may be based on a linear numeric step process (such as Pascal), or the user defines the iteration step and the abort condition (such as C), and the Python for statement iterates over the subkeys in any sequence (linked list or string) in the order in which they are in the sequence. For example (no allusion):
# Measure Some strings:...words = ['cat''window' defenestrate'] for in words: ... Print 3612
It is unsafe to modify the iteration sequence during the iteration (only if a mutable sequence such as a linked list is used). If you want to modify the sequence of your iteration (for example, to copy a selection), you can iterate over its copy. It is easy to do this with the cut logo:
for in words[:]: # Loop over a slice copy of the entire list. ... if len (w) > 6: ... Words.insert (0, W) ... >>> words['defenestrate'cat' 'window' 'defenestrate']
Range () function
If you need a numeric sequence, the built-in function range () is handy, and it generates a arithmetical progression linked list:
for in range (5): ... Print (i) ... 01234
range generates a linked list of 10 values that is populated with the index value of the linked table with a 10-length listing, which does not include the end value in the range. You can also let the range () operation start with another value, or you can specify a different step value (even a negative number, sometimes called a "step"):
Range (5, ten) 5 through 9, 3) 3, 6, 9range (-10, -100, -30) -10,-40,-70
If you need to iterate the linked list index, use range () and Len () as shown below
>>> a = ['Mary','had','a','Little','Lamb']>>> forIinchRange (len (a)): ...Print(i, a[i]) ... 0 Mary1had2a3Little4 Lamb
Strange things happen if you just print a sequence:
Print (Range (10)
In different ways the range () function returns an object that behaves as if it were a list, but in fact it is not. When you iterate over it, it is an object that can return successive items like the desired sequence, but it does not really construct the list in order to save space.
We call such objects to be iterative , that is, to be a target (parameter) of a function or structure that expects to get successive entries from something to the end. The For statement we have seen is such an iterator. The list () function is another ( iterator ) that creates lists from an iteration (object):
>>> List (range (51, 2, 3, 4)
Routines:
1My_age = 232 3 forIinchRange (3):4age = Int (input ("Guess Age:"))5 ifMy_age = =Age :6 Print("You got it ...")7 Break8 elifMy_age >Age :9 Print("Think older ...")Ten Else: One Print("think younger ...") A Else: - Print("You tried too much")
Python Fundamentals (iii) Process Control (3)--for