转载请注明出处:http://blog.csdn.net/cxsydjn/article/details/71303117
Loops allow you to quickly iterate over information in Python. The note will cover two types of loop: ‘while’ and ‘for’.
Python notes of open courses @Codecademy.
Exit Method 1: Condition
The condition is the expression that decides whether the loop is going to be executed or not.Example:
while loop_condition: # Do something for each loop # until loop_condition = FalseExit Method 2: break
First, create a while with a condition that is always true. The simplest way is shown.Using an if statement, you define the stopping condition. Inside the if, you write break, meaning “exit the loop.”The difference here is that this loop is guaranteed to run at least once.Example:
while True: # Do something for each loop if loop_condition == False: breakwhile/else: 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.An alternative way to loop is the for loop.
The syntax is as shown; this example means “for each x in a, do sth”.The above a could be a list, a string or a dictionary, etc.
# A sample loop would be structured as follows. for x in a: # Do something for every xenumerate:
for index, item in enumerate(list):It works by supplying a corresponding index to each item in the list.zip:
for a, b in zip(list_a, list_b):It will create pairs of elements when passed two lists, and will stop at the end of the shorter list. It can handle three or more lists.for/else:
Just like with while, for loops may have an else associated with them.In this case, the else statement is executed after the for, but only if the for ends normally — that is, not with a break.