Welcome to the - 23rd meeting of CC Lab 2007! (we are into negative numbers now…). We will cover three basic things in this session:. Conditionals Functions Modules.
So what are conditionals?Conditionals are blocks of code in Python (or any programming language) that are only run if a certain condition is met.
Step though this for loop example and note what is executed:
>>> # Measure some strings:
... a = [’cat’, ’window’,’defenestrate’]
>>> for x in a:
... print x, len(x)
The ‘range’ function:
If you need to iterate over a sequence of numbers, the built-in functionrange()comes in handy. It generates lists containing arithmetic progressions:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The given end point is never part of the generated list;range(10)generates a list of 10 values, exactly the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the ‘step’):
>>> range(5, 10)
[5, 6, 7, 8, 9]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100, -30)
[-10, -40, -70]
Step through this use of ‘len’ and ‘range’:
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print i, a[i]
Break and continue statements:
The ‘break’statement breaks out of the smallest enclosingfororwhileloop.
The ‘continue’statement continues with the next iteration of the loop. It is allowed only inside a loop body.
Check out this very cool code snippet from Guido van Rossum (the author of Python). It uses ‘range’, ‘break’, and ‘else’:
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print n, ’equals’, x, ’*’, n/x
... # loop fell through without finding a factor
... print n, ’is a prime number’
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
As we code these various loops, it’s nice to use some abbreviations. These are known as shorthand operators. Figure out what is happening in the following:starter = triangle = liner = 0while starter < 10: starter += 1 triangle += starter print starter,triangle, liner += 1 liner %= 2 if not liner: print "."
A function is a named sequence of statements that performs a computation. When you define a function, you specify the name and the sequence of statements. Later, you can ‘call’ the function by name:len(x)(‘len’ is a built in Python function)
Why Functions?It may not be clear why it is worth the trouble to divide a program into functions. There are a lot of reasons; here are a few:• Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read and debug. • Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place. • Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole. • Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it.
There are many built-in Python functions such as:len(x)You can find a list of all the built-in functions in the python reference manuals on python.org
So say we want a function that does something special, that we need to “call” many times. Well, we can write our own:def print_stupid_exclamations(): print ”Lo dee do dee diddle dee doo." print ”Skim bickle boo dee doo dee doo.” print ”Flim flee floo flah!" ’def’ is a keyword that indicates that this is a function definition. The name of the function is print_stupid_exclamations. The empty parentheses after the name indicate that this function doesn’t take any arguments.
def print_stupid_exclamations(): print ”Lo dee do dee diddle dee doo." print ”Skim bickle boo dee doo dee doo.” print ”Flim flee floo flah!" The first line of the function definition is called the header; the rest is called the body. The header has to end with a colon and the body has to be indented. The body can take any number of statements.Once you have defined a function, Python creates a variable of the same name. So you can call it:>>>print_stupid_exclamations()Lo dee do dee diddle dee doo. Skim bickle boo dee doo dee doo.Flim flee floo flah!
You can define functions that you send ‘parameters’ and ‘arguments’ to, just like we do to the built-in ones:len(x)Functions can take any number of arguments.
Inside the function, the arguments are assigned to variables called parameters. Here is an example of a user-defined function that takes an argument: def print_thrice(gwodly): print gwodly print gwodlyprint gwodlyAnd then it’s use:>>>print_thrice(‘slochjor tichjis trew’)slochjor tichjis trewslochjor tichjis trewslochjor tichjis trew
As noted, you can assign any number of arguments to a function. Within the function, variables are typed to their usage (int, list, string, etc.), and they are local to the function, which means you can’t call (or refer) to them outside the function.
So far, we’ve just sent values to a function. You can return values from a function (step through this code):>>>def getlist():… a,b,c = (3,4),(4,5),(5,6)… return [a,b,c]>>>g,h,i = getlist()>>>print h5
Flow of execution
In order to ensure that a function is defined before its first use, you have to know the order in which statements are executed, which is called the flow of execution.
Execution always begins at the first statement of the program. Statements are executed one at a time, in order from top to bottom.
Function definitions do not alter the flow of execution of the program, but remember that statements inside the function are not executed until the function is called.
Modules in PythonThe easiest way to picture a module is as a place you can store code (varibles, constants, functions, etc.). You ‘import’ a module into your program. There are both modules that come with Python, and modules that you create yourself. Just save whatever you want in your module as a normal Python file.
Python has a math module that provides most of the familiar mathematical functions. A module is a file that contains a collection of related functions. Before we can use the module, we have to import it:
>>> import math
This statement creates a module ob ject named math. If you print the module object, you get some information about it:
>>> print math
<module ’math’ from ’/usr/lib/python2.4/lib-dynload/mathmodule.so’>
The module object contains the functions and variables defined in the module. To access one of the functions, you have to specify the name of the module and the name of the function, separated by a dot (also known as a period). This format is called dot notation.
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
This example computes the logarithm base 10 of the signal-to-noise ratio. The math module also provides a function called log that computes logarithms base e.
>>> radians = 0.7
>>> height = math.sin(radians)
This example finds the sine of radians. The name of the variable is a hint that sin and the other trigonometric functions (cos, tan, etc.) take arguments in radians. To convert from degrees to radians, divide by 360 and multiply by 2π:
>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
The expression math.pi gets the variable pi from the math module. Conveniently, the value of this variable is an approximation of π, accurate to about 15 digits.
Onwards to your next homework assignment. This assignment will have three problems. Parts two and three are connected…It is due in two weeks.