cs190/295 programming in python for life sciences: lecture 5

62
CS190/295 Programming in Python for Life Sciences: Lecture 5 Instructor: Xiaohui Xie University of California, Irvine

Upload: rosalyn-morrow

Post on 31-Dec-2015

32 views

Category:

Documents


3 download

DESCRIPTION

CS190/295 Programming in Python for Life Sciences: Lecture 5. Instructor: Xiaohui Xie University of California, Irvine. Announcements. Homework assignment #3 will be out by the end of Wed (Feb 1). Due on Feb 7 (Tue) before class. Q/A Lab Session on this Thursday. So bring your laptop. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CS190/295  Programming in Python for Life Sciences: Lecture 5

CS190/295 Programming in Python for Life Sciences: Lecture 5

Instructor: Xiaohui Xie

University of California, Irvine

Page 2: CS190/295  Programming in Python for Life Sciences: Lecture 5

Announcements

• Homework assignment #3 will be out by the end of Wed (Feb 1). Due on Feb 7 (Tue) before class.

• Q/A Lab Session on this Thursday. So bring your laptop.

Page 3: CS190/295  Programming in Python for Life Sciences: Lecture 5

Defining Functions

Page 4: CS190/295  Programming in Python for Life Sciences: Lecture 5

Functions, Informally

• You can think of a function as a subprogram—a small program inside of a program. The basic idea of a function is that we write a sequence of statements and give that sequence a name. The instructions can then be executed at any point in the program by referring to the function name.

• The part of the program that creates a function is called a function definition. When a function is subsequently used in a program, we say that the definition is called or invoked.

• A single function definition may be called at many different points of a program.

Page 5: CS190/295  Programming in Python for Life Sciences: Lecture 5

Functions – simple example

Examples: “Happy Birthday” song. The standard lyrics look like this.

Happy birthday to you!

Happy birthday to you!

Happy birthday, dear <insert-name>.

Happy birthday to you!

Page 6: CS190/295  Programming in Python for Life Sciences: Lecture 5

Functions – simple example

Page 7: CS190/295  Programming in Python for Life Sciences: Lecture 5

Parameters of a function

Page 8: CS190/295  Programming in Python for Life Sciences: Lecture 5

• A function definition looks like this:

• A function is called by using its name followed by a list of actual parameters or arguments

• A function can have several parameters (arguments):

• The actual parameters are matched up with the formal parameters by position

Functions and Parameters

def <name>(<formal-parameter-1>,…,<formal-parameter-n>)

<name>(<actual-parameter-1>,…,<actual-parameter-n>)

Page 9: CS190/295  Programming in Python for Life Sciences: Lecture 5

When a function is called

When Python comes to a function call, it initiates a four-step process.

1. The calling program suspends at the point of the call.

2. The formal parameters of the function get assigned the values supplied by the actual parameters in the call.

3. The body of the function is executed.

4. Control returns to the point just after where the function was called.

Page 10: CS190/295  Programming in Python for Life Sciences: Lecture 5

Functions with return values

Using return statement:

Page 11: CS190/295  Programming in Python for Life Sciences: Lecture 5

Functions can return more than one value

When calling this function, place it in a simultaneous statement:

Page 12: CS190/295  Programming in Python for Life Sciences: Lecture 5

Scope of variablesThe difference between global and local variables:•Global variables are accessible inside and outside of functions•Local variables are accessible only inside the function

Page 13: CS190/295  Programming in Python for Life Sciences: Lecture 5

Scope of variablesIf a global variable is used inside a function, Python actually creates a new local variable, and will not change of the value of the global variable.

Page 14: CS190/295  Programming in Python for Life Sciences: Lecture 5

How to set a global variable with in a function?

To set a global variable inside a function, use global statement, which declares that the inner variable has the module scope.

Page 15: CS190/295  Programming in Python for Life Sciences: Lecture 5

Nested functionsScoping for nested functions work similarly:

Page 16: CS190/295  Programming in Python for Life Sciences: Lecture 5

Nested functions

Page 17: CS190/295  Programming in Python for Life Sciences: Lecture 5

Nested functions

However, note that use global statement inside nested functions will not reset the outer variable

Page 18: CS190/295  Programming in Python for Life Sciences: Lecture 5

Control Structures

Part I: Decision structures

Page 19: CS190/295  Programming in Python for Life Sciences: Lecture 5

Motivation

• So far, we have viewed computer programs as sequences of instructions that are followed one after the other. Sequencing is a fundamental concept of programming, but alone, it is not sufficient to solve every problem.

• Often it is necessary to alter the sequential flow of a program to suit the needs of a particular situation. This is done with special statements known as control structures.

• Decision structures, one type of control structures, are statements that allow a program to execute different sequences of instructions for different cases,

Page 20: CS190/295  Programming in Python for Life Sciences: Lecture 5

An example: temperature warning

Suppose now we want to enhance the program by providing temperature warning like this:

Page 21: CS190/295  Programming in Python for Life Sciences: Lecture 5

Flowchart of the temperature conversion program with warning

Page 22: CS190/295  Programming in Python for Life Sciences: Lecture 5

The temperature conversion program with warning

decision structure

Page 23: CS190/295  Programming in Python for Life Sciences: Lecture 5

Simple if-statement

Control flow of simple if-statement:

Page 24: CS190/295  Programming in Python for Life Sciences: Lecture 5

Forming simple conditions• Simple conditions that compare the values of two expressions:

<expr> <relop> <expr>

• <relop> is short for relational operator. There are six relational operators in Python:

• Conditions may compare either numbers or strings. When comparing strings, the ordering is lexicographic. Basically, this means that strings are put in alphabetic order according to the underlying ASCII codes. So all upper-case letters come before lower case letters (e.g., “Bbbb” comes before “aaaa”, since “B” precedes “a”).

Page 25: CS190/295  Programming in Python for Life Sciences: Lecture 5

Boolean expression

• Conditions are actually a type of expression, called a Boolean expression

• When a Boolean expression is evaluated, it produces a value of either True (the condition holds) or False (it does not hold).

Page 26: CS190/295  Programming in Python for Life Sciences: Lecture 5

Boolean operators

• Python provides three Boolean operators: and, or and not.

• The Boolean operators and and or are used to combine two Boolean expressions and produce a Boolean result.

<expr> and <expr>

<expr> or <expr>

– The and of two expressions is true exactly when both of the expressions are true.

– The or of two expressions is true when either expression is true

• The not operator computes the opposite of a Boolean expression. It is a unary operator, meaning that it operates on a single expression.

Page 27: CS190/295  Programming in Python for Life Sciences: Lecture 5

Precedence of Boolean operators

• Build arbitrarily complex Boolean expressions using Boolean operators

• Consider this expression:

a or not b and c

• Python follows a standard convention that the order of precedence is: not, followed by and, followed by or. So the expression would be equivalent to this parenthesized version.

(a or ((not b) and c))

• I suggest that you always parenthesize your complex expressions to prevent confusion.

Page 28: CS190/295  Programming in Python for Life Sciences: Lecture 5

Two-way decisions: if-else statement

When the Python interpreter encounters this structure, it will first evaluate the condition.

•If the condition is true, the statements under the if are executed.

•If the condition is false, the statements under the else are executed.

•In either case, control then passes to the statement following the if-else

Page 29: CS190/295  Programming in Python for Life Sciences: Lecture 5

Two-way decisions: example

Page 30: CS190/295  Programming in Python for Life Sciences: Lecture 5

Two-way decisions: an example

Page 31: CS190/295  Programming in Python for Life Sciences: Lecture 5

Multi-way decisions: if-elif-else

• Python will evaluate each condition in turn looking for the first one that is true. If a true condition is found, the statements indented under that condition are executed, and control passes to the next statement after the entire if-elif-else.

• If none of the conditions are true, the statements under the else are performed.

• The else clause is optional; if omitted, it is possible that no indented statement block will be executed.

Page 32: CS190/295  Programming in Python for Life Sciences: Lecture 5

Control Structures

Part 2: Loop Structures

Page 33: CS190/295  Programming in Python for Life Sciences: Lecture 5

For Loops

• It allows us to iterate through a sequence of values

• The loop index variable var takes on each successive value in the sequence, and the statements in the body of the loop are executed once for each value.

Page 34: CS190/295  Programming in Python for Life Sciences: Lecture 5

For Loop example: computer the average of a series of numbers

Page 35: CS190/295  Programming in Python for Life Sciences: Lecture 5

Indefinite Loops: while-statement

• An indefinite loop keeps iterating until certain conditions are met.

• Here condition is a Boolean expression, just like in if statements. The body is, as usual, a sequence of one or more statements.

• The body of the loop executes repeatedly as long as the condition remains true. When the condition is false, the loop terminates

Page 36: CS190/295  Programming in Python for Life Sciences: Lecture 5

Indefinite loop example: computing the average of a series of numbers

Page 37: CS190/295  Programming in Python for Life Sciences: Lecture 5

Indefinite loop example: computing the average of a series of numbers

Another implementation:

Page 38: CS190/295  Programming in Python for Life Sciences: Lecture 5

File LoopsOne disadvantage of all the averaging programs presented so far is that they are interactive. A better approach to the problem is to type all of the numbers into a file. The data in the file can be perused and edited before sending it to a program that generates a report.

Page 39: CS190/295  Programming in Python for Life Sciences: Lecture 5

File Loops• One potential problem with readlines()is that the entire contents of the

file are first read into main memory. • With very large data files, it is better to read and process small sections of

the file at a time. In the case of text files, a simple approach is to process the file one line at a time

• The readline method gets the next line from a file as a string. When we come to the end of the file, readline returns an empty string.

Page 40: CS190/295  Programming in Python for Life Sciences: Lecture 5

Nested LoopsAgain in the number averaging example, suppose instead of one-per-line we allow any number of values on a line, separated by comma.

Page 41: CS190/295  Programming in Python for Life Sciences: Lecture 5

Post-Test LoopSuppose you are writing an input algorithm that is supposed to get a nonnegative number from the user. If the user types an incorrect input, the program asks for another value. It continues to reprompt until the user entersa valid value. This process is called input validation.

Here is a simple algorithm:repeat get a number from the useruntil number is >= 0

Page 42: CS190/295  Programming in Python for Life Sciences: Lecture 5

Post-Test Loop• Python does not have a statement that directly implements a post-test loop. However you can implemented with a while statement using the trick of

“seeding”:

• Or use the break statement:

Page 43: CS190/295  Programming in Python for Life Sciences: Lecture 5

Data Collections

Page 44: CS190/295  Programming in Python for Life Sciences: Lecture 5

Most real-world programs deal with large collections of data

A few examples:

•Words in a document.•Students in a course.•Data from an experiment.•Customers of a business.•Graphics objects drawn on the screen.•Cards in a deck.

Page 45: CS190/295  Programming in Python for Life Sciences: Lecture 5

Example problem: simple statistics

Extend this program so that it computes not only the mean, but also the median and standard deviation of the data

Page 46: CS190/295  Programming in Python for Life Sciences: Lecture 5

Lists

• Lists are ordered sequences of items, a collection of values denoted by the enclosing square brackets

• Lists can be created by listing items inside square brackets

Page 47: CS190/295  Programming in Python for Life Sciences: Lecture 5

Lists vs. Strings

• In Python strings and lists are both sequences that can be indexed. In fact, all of the built-in string operations that we discussed previously are sequence operations and can also be applied to lists:

Page 48: CS190/295  Programming in Python for Life Sciences: Lecture 5

Lists vs. Strings: differences• The items in a list can be any data type, including instances of programmer-defined classes. Strings, obviously, are always

sequences of characters.

• Second, lists are mutable. That means that the contents of a list can be modified. Strings cannot be changed “in place.”

Page 49: CS190/295  Programming in Python for Life Sciences: Lecture 5

Tuples

• A tuple is a sequence of immutable Python objects. Just like lists. The only difference is that types cannot be changed.

• Tuples are defined using parentheses while lists use square brackets.

• Examples:Tup1 = (1,2,3,4)

Tup2 = (‘UCI’, ‘UCLA,’UCSD’)

Page 50: CS190/295  Programming in Python for Life Sciences: Lecture 5

List operations

• Python lists are dynamic. They can grow and shrink on demand. They are also heterogeneous. You can mix arbitrary data types in a single list. In a nutshell, Python lists are mutable sequences of arbitrary objects. This is very different from arrays in other programming languages.

• A list of identical items can be created using the repetition operator.

• Typically, lists are built up one piece at a time using the append method.

Page 51: CS190/295  Programming in Python for Life Sciences: Lecture 5

List operations: remove elements

Page 52: CS190/295  Programming in Python for Life Sciences: Lecture 5

List operations

Page 53: CS190/295  Programming in Python for Life Sciences: Lecture 5

Using lists is easy if you keep these basic principles in mind

• A list is a sequence of items stored as a single object.

• Items in a list can be accessed by indexing, and sublists can be accessed by slicing.

• Lists are mutable; individual items or entire slices can be replaced through assignment statements.

• Lists will grow and shrink as needed.

Page 54: CS190/295  Programming in Python for Life Sciences: Lecture 5

Statistics with Lists

# get a list of numbers and store in a list

Page 55: CS190/295  Programming in Python for Life Sciences: Lecture 5

Statistics with Lists: Mean

Page 56: CS190/295  Programming in Python for Life Sciences: Lecture 5

Statistics with Lists: Standard Deviation

Page 57: CS190/295  Programming in Python for Life Sciences: Lecture 5

Statistics with Lists: Median

Page 58: CS190/295  Programming in Python for Life Sciences: Lecture 5

Simple Statistics: put together

Page 59: CS190/295  Programming in Python for Life Sciences: Lecture 5

Non-sequential collections• Dictionary is a build-in data type for non-sequential collections in Python.

• Python dictionaries are mappings: Keys -> values

• A dictionary can be created by listing key-value pairs inside a curly braces.

• We can access the value associated with a particular key using:

• Dictionaries are mutable:

Page 60: CS190/295  Programming in Python for Life Sciences: Lecture 5

Dictionary Operations

• You can also extend a dictionary by adding new entries

• In fact, a common method for building dictionaries is to start with an empty collection and add the key-value pairs one at a time

Page 61: CS190/295  Programming in Python for Life Sciences: Lecture 5

Dictionary Operations

Page 62: CS190/295  Programming in Python for Life Sciences: Lecture 5

Dictionary methods: examples