For loops
for loops in Python are more general in that the lower and upper bounds are not explicitly specified in the for line. The break and continue keywords are available with for loops, just like in while loops.
trees = ["oak", "maple", "pine", "cherry"]
for x in trees:
print(x)
# the result is that all four tree names are printed, even though the command never said start at integer 1 and end at integer 4. Again, this reads more like it is English than code.
It turns out that the loop dummy variable in a for loop has global scope, meaning, you can use it and modify it even after the for loop is done.
trees = ["oak", "maple", "pine", "cherry"]
for x in trees:
print(x)
print(x)
# will print cherry twice in a row.
If you look closely though and try to use a for loop variable in an unorthodox way, it is subject to a counting process and ordering (ranking) from left to right. It is almost like behind the scenes it is progressing through an integer count from the number 0 to the number of items in the list. There's a rank from left to right.
animals = ["cat", "sheep", "lion"]
for x in animals:
if x > "sheep":
continue
print(x)
# the loop above will skip printing lion because lion is to the
# right of sheep, and thus is considered of a higher rank, or
# greater than sheep!!
If you prefer to have start and stop numbers in the for loop, use the range keyword.
trees = ["oak", "maple", "pine", "cherry"]
for x in range(0,4):
print(trees[x]) # here is an index, rather than the list element
# will print all the four trees
You can also use range with just one argument. In that case it assumes you want to start at 0.
range(3) covers 0 1 2
Also, a third argument to range tells it the step size between elements as the for loop iterates.
range(3,4,13) covers 3 7 11
In either case, remember that the right side argument is NOT included in the loop iteration:
range(0,7) covers 0 1 2 3 4 5 6
Much like in a while loop the else clause and the pass keywords are available.
No comments:
Post a Comment