1 / 39

# Welcome to the - 23rd meeting of CC Lab 2007! (we are into negative numbers now…) - PowerPoint PPT Presentation

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.

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

Welcome to the - 23rd meeting of CC Lab 2007! (we are into negative numbers now…)

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

### 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.

### We will discuss:

• what is truth if statements blocks in Python else and elif for statements while loops break and continue shorthand operators

• You may have dealt with some of these conditionals before.

• Though the syntax will change from programming language to programming language, the fundamentals will remain the same. You can apply the same concepts to Actionscript,

• Mel (Maya), C++, or Java

• In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability.

• First, what is truth?

• Truth value testing is a binary by nature. Either something is or is not. Every object in Python may be tested for its truth value.

• The following values are naturally considered false in Python:

• None

• False

• zero of any numeric type, for example, 0 or 0.0

• any empty sequence (e.g., '', (), or [])

• Usually we check the truth of a “comparison”. We compare two numbers, or a variable and a number.

• Does a equal b?

• Is c less than d?

• Is e greater than 23?

• This test then forms the trigger for conditional loops such as if or while.

### Boolean operators in Python:

• (Common comparison operators)

• OperatorDescriptionExample

• <less thani < 100

• <=less than or equal toi <= 100

• >greater thani > 100

• >=greater than or equal toi >= 100

• ==equality i == 100

• !=inequality (also <>)i != 100

### if statements:

• The simplest form is the if statement:

• if x > 0:

• print ’x is positive’

• The boolean expression after the if statement is called the condition. If it is true, then the indented statement gets executed. If not, nothing happens.

• If statements have the same structure as function definitions: a header followed by an indented block. Statements like this are called compound statements.

### Blocks in Python:

• In the following if statement, the indented code following the colon is the “block”

• if x > 0:

• print ’x is positive’

• print ‘Gall durnit, slam bang!’

• The block can be as long or as complicated as you need. The minute you break out of the indentation, you leave the block:

• if x > 0:

• print ’x is positive’

• print ‘Gall durnit, slam bang!’

• print ‘Out of the block now…’

### else and elif :

• In the following if statement, we use elif and else commands to extend the if conditional:

• faren = input("Enter a temperature in Fahrenheit:") print "That degrees converts to:"

• if faren > 212:

• print "Steam"

• elif faren > 112:

• print "Very Hot Water"

• elif faren > 32:

• print "Water"

• else:

• print "Ice"

• print "Program completed"

• for statements

• The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.

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)

...

cat 3

window 6

defenestrate 12

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:

>>> range(10)

[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]

...

0 Mary

2 a

3 little

4 lamb

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

... break

... else:

... # 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 "."

### FunctionsYou’ve noticed that we refer to various commands we have introduced as “functions” (‘range’, ‘len’, ‘sort’, etc.)

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 h[1]5

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.

### Module example

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

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.

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