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.
While Loops
-
The
while
loop is similar to anif
statement: it executes the code inside of it if some condition is true. -
The difference is that the
while
loop will continue to execute as long as the condition is true. In other words, instead of executing if something is true, it executes while that thing is true. -
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 = False
-
-
Exit 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 theif
, you writebreak
, 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: break
-
-
while
/else
:- Python is the
while
/else
construction.while
/else
is similar toif
/else
, but there is a difference:- the
else
block will execute anytime the loop condition is evaluated toFalse
. 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
, theelse
will not be executed.
- the
- Python is the
For Loops
-
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 x
-
-
enumerate
:for index, item in enumerate(list):
- It works by supplying a corresponding
index
to eachitem
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 anelse
associated with them. - In this case, the
else
statement is executed after thefor
, but only if thefor
ends normally — that is, not with abreak
.
- Just like with
网友评论