Graphics Reference
In-Depth Information
overanumericalsequence,youcandosobyusingthe
range()
function,whichreturnsalistofintegervalues
between two integer values (not inclusive of the second one), as shown here:
>>> for num in range(1,5):
... print(num)
...
1
2
3
4
An optional third integer argument to
range()
can be used to set the step length of the range. The default
is
1
. If you want to count off by two or three, you can adjust the step length.
Conditionalsaresetbyusing
if/elif/else
statements.Inthisexample,Pythoniteratesthroughthenum-
bers 0 to 9 with a step length of two. For each number, the interpreter checks to see whether the number is less
thanorequalto2,greaterthanorequalto8,orneither.The
elif
statementisPython's
else if
conditional.Note
particularly the left indentation. The
if
,
elif
, and
else
statements must all be aligned along the left side in
order to correspond to each other. If the left indentation of those lines does not match, this code will result in an
error.
>>> for num in range(0,10,2):
if num <= 2:
print (str(num) + " is small")
elif num >= 8:
print (str(num) + " is big")
else:
print (str(num) + " is medium")
0 is small
2 is small
4 is medium
6 is medium
8 is big
A handy statement for programming is the
pass
statement. This statement is a placeholder that does noth-
ing, but it can stand in for other code in a control structure when having no command would result in an indent-
ation error.
Other control flow statements are available for use in Python, such as
while
and some modifications to
the standard
for
loop. However, for the purposes of the content of the next few chapters,
for
loops and
if/
elif/else
constructions will be sufficient to know about. For further information, please refer to the Python
resources mentioned at the beginning of the chapter.
Functions
Much of programming in Python involves defining functions of your own, which can then be called elsewhere,
including from within other functions. You can define a function on the command line with the
def
keyword
like this: