While / else
Something completely different about Python is the while/else construction. while/else is similar to if/else, but there is a difference: the else block will execute anytime the loop condition is evaluated to False. This means that it will execute if the loop is never entered or if the loop exits normally. If the loop exits as the result of a break, the else will not be executed.
word = "Marble"
for char in word:
print char,
The, character after our print statement means that our next print statement keeps printing on the same line.不加逗号的话默认会打印完换行。
A weakness of using for-each style of iteration is that you don't know the index of the thing you're looking at. 不知道遍历到了第几个。enumerate works by supplying a corresponding index to each element in the list that you pass it. Each time you go through the loop, index will be one greater, and item will be the next item in the sequence. It's very similar to using a normal for loop with a list, except this gives us an easy way to count how many items we've seen so far.
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
print index, item
打印结果
Your choices are:
0 pizza
1 pasta
2 salad
3 nachos
It's also common to need to iterate over two lists at once. This is where the built-in zip function comes in handy.
zip will create pairs of elements when passed two lists, and will stop at the end of the shorter list.
zip can handle three or more lists as well!
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_a, list_b): #zip会返回一对数字,如3,2 9,4 17,8 15,10 19,30然后就结束循环,因为shorter list已经end了~
if a > b:
print a
else:
print b
Just like with while, for loops may have an else associated with them.
The else statement is executed after the for, but only if the for ends normally—that is, not with a break. This code will break when it hits 'tomato', so the else block won't be executed.所以如果不想让else块里的语句执行,就在for循环体里使用break跳出即可。
posted on
浙公网安备 33010602011771号