1 / 39

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

## PowerPoint Slideshow about '' - giuseppe-bishop

An Image/Link below is provided (as is) to download presentation

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 - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Welcome to the -23rdmeeting of CC Lab 2007!(we are into negative numbers now…)

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

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

• First, what is truth? ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability.

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

Boolean operators in Python: two numbers, or a variable and a number.

• (Common comparison operators)

• Operator Description Example

• < less than i < 100

• <= less than or equal to i <= 100

• > greater than i > 100

• >= greater than or equal to i >= 100

• == equality i == 100

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

if statements: two numbers, or a variable and a number.

• 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: two numbers, or a variable and a number.

• 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 two numbers, or a variable and a number. :

• 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 two numbers, or a variable and a number.

• 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: two numbers, or a variable and a number.

>>> # Measure some strings:

... a = [’cat’, ’window’,’defenestrate’]

>>> for x in a:

... print x, len(x)

...

cat 3

window 6

defenestrate 12

The ‘range’ function two numbers, or a variable and a number. :

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’: two numbers, or a variable and a number.

>>> 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: two numbers, or a variable and a number.

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 two numbers, or a variable and a number. 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 "."

Functions abbreviations. These are known as You’ve noticed that we refer to various commands we have introduced as “functions” (‘range’, ‘len’, ‘sort’, etc.)

A function is a abbreviations. These are known as 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? abbreviations. These are known as 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: abbreviations. These are known 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(): we need to “call” many times. Well, we can write our own: 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 gwodly print 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 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. 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 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.

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 Python 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. The 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 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.

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

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