Program control: Looping, conditionals and functions
Categories: Python
Program control: Looping, conditionals and functions
Now we’re ready for some more involved programming constructions. The basic technique for writing a loop is illustrated by the following example, which prints out the integers from 0 through 9:
for i in range(10):
x = i*i
print i,x
Note that in Python, indentation is part of the syntax. In the above example, the indentation is the only way Python has to identify the block of instructions that is being looped over. Indentation in a block of code must line up, and you need to be cautions not to confuse spaces and tabs. The use of indentation as a syntactic element in Python enforces code readability and reduces the need for special identifiers to terminate blocks.
The construct range(10) is actually shorthand for the 10-element list
[0,1,2,3,4,5,6,7,8,9]
In fact, one of Python’s many charms is that a for loop can loop over the elements of any list at all, regardless of what the elements of the list may be. Thus, the following example sums up the length of four strings:
myList = [’bob’,’carol’,’ted’,’alice’]
n = 0
for name in myList:
n = n + len(name)
This can be very useful for looping over file names with data needing to be processed, or data arrays which need something done to them, and all sorts of other things that will occur to you once you get accustomed to the concept. An alternate to looping over a list is to use the while construction, as in:
x = 1.
while x < 100.:
print x
x = 1.1*x
Now, for practice, write a loop to compute 52 factorial (i.e. 52*51*...*1). Note that Python automatically starts using long integers when it needs to. In doing computations, it is typical that one needs to test for the satisfaction of a condition at some point before proceeding. For example, one might need to test
whether a temperature is below or above freezing to decide whether to form ice or liquid water. Programming languages generally provide some conditional control to handle this situation, and Python is no exception. The following illustrates the use of an if block in Python:
if T < 273.15:
print "Too cold!"
and an extended if block:
if T < 273.15:
print "Too cold!"
elif T > 373.15:
print "Too hot!"
else:
print "Just right!"
An if block can have as many elif blocks as you need, and the conditional being tested can be anything that reasonably evaluates to a truth value. To distinguish from assignment, the equality relation is expressed by the symbol ==. The symbols <= and >= have the obvious meanings. The exclamation point negates a relation, and Python also provides the operator not to negate the truth value of an arbitrary
logical expression. For example 1 != 0 and not (1 == 0) mean the same thing. Compound expressions can be built up from the Boolean operators for ”and” (&) and ”or” (|, the vertical bar). Python also provides the keywords True and False for logical values, but regular integers 1 and 0 generally do just as well in conditionals.
The organization of almost any program can benefit from the subdivision of the labor of the program into a number of functions. This makes the program easier to debug, since functions can be tested individually. It also allows the re-use of code that is needed in many different places in the program. The basic means of defining a function is illustrated in the following example, which returns the square of the argument:
def f(x):
return x*x
From the command line, you would invoke this function, once it is defined, by typing, e.g. f(3).
Python can even handle recursion in functions. That is, functions can be defined in terms of themselves. As an example, a function to compute the factorial of n could be written: def factorial(n):
if n == 0:
return 1
else:
return n*factorial(n-1)
Functions can return multiple arguments, as in:
def powers(x):
return x,x*x,x*x*x
This returns a tuple containing the three values. It can be very nicely used with Python’s ability to set multiple items to corresponding items of a tuple, using constructions of the form:
x1,x2,x3 = powers(2)
Python functions work only on a copy of the arguments. It is important to keep this in mind, since it means that any changes made to these arguments (”sideeffects”) do not affect the variable’s value in the calling program. Try this:
def f(myValue):
myValue = 0
x = 1
print x
f(x)
print x
In this example, x is unchanged because functions work only on a local copy of their arguments. However, if the argument is a name which points to the location of some data, the data pointed to can be modified in the function. This may seem somewhat arcane, but the following simple example modifying an element in a list should illustrate the general principle:
def f(myList):
myList[0] = myList[1]
L = [1,2,3,4,5]
f(L)
print L
If you want to replace the list with a completely new list, based on the old one, the right way to do this is to return the new list, rather than doing anything to the argument:
def bump(myList):
newList = [ ]
for item in myList:
newList.append(item+1)
return newList