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

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

Upload: clancy

Post on 14-Jan-2016

35 views

Category:

Documents


1 download

DESCRIPTION

CS190/295 Programming in Python for Life Sciences: Lecture 3. Instructor: Xiaohui Xie University of California, Irvine. Announcements. The enrollment max cap for CS295 has been increased to 45. - PowerPoint PPT Presentation

TRANSCRIPT

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

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

Instructor: Xiaohui Xie

University of California, Irvine

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

Announcements

• The enrollment max cap for CS295 has been increased to 45.

• Homework assignment #2 will be posted online by 5pm Friday, which will be due Jan 16 (Thur) before class.

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

Computing with Numbers

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

Numeric Data Types

Example output:

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

Numeric Data Types

• Whole numbers are represented using the integer data type (int for short).Values of type int can be positive or negative whole numbers.

• Numbers that can have fractional parts are represented as floating point (or float) values.

• The data type of an object determines what values it can have and what operations can be performed on it.

• The float type only stores approximations. There is a limit to the precision, or accuracy, of the stored values. By contrast, the int type is exact.

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

Numeric Data Types

• Notice how operations on floats produce floats, and operations on ints produce ints.

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

Using the Math LibraryPython provides many other useful mathematical functions in a special math library. A library is just a module that contains some useful definitions.

Example: find the roots of ax2+bx+c =0

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

Using the Math LibraryPython provides many other useful mathematical functions in a special math library. A library is just a module that contains some useful definitions.

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

Accumulating Results: Factorial• In mathematics, factorial is often denoted with an exclamation (“!”). The

factorial of a whole number is defined as n!=n(n-1)(n-2)…(1). This happens to be the number of distinct arrangements for n items. Given six items, we compute 6! =720 possible arrangements.

• Write a program that will compute the factorial of a number entered by the user. The basic outline of our program follows an Input-Process-Output pattern.

• Basic strategy: do repeated multiplications, use an accumulator variable + a loop structure

Input number to take factorial of, nCompute factorial of n, factOutput fact

Initialize the accumulator variableLoop until final result is reachedupdate the value of accumulator variable

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

Accumulating Results: FactorialInitialize the accumulator variableLoop until final result is reachedupdate the value of accumulator variable

For example, suppose we want to calculate 5!=5*4*3*2*1

We define a variable and initialize it to be 1

fact = 1

for factor in [2,3,4,5] fact = fact * factor

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

Python range() function

• range(n): produce a sequence of numbers starting with 0 and continuing up to, but not including n

• range(start, n): produce a sequence of numbers starting with start and continuing up to, but not including n

• range(start, n, step): produce a sequence of numbers starting with start and continuing up to, but not including n, and using step as the increment between numbers

Examples:

>>> range(10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> range(5,10)

[5, 6, 7, 8, 9]

>>> range(5,10,3)

[5, 8]

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

Accumulating Results: Factorial• n!=n(n-1)(n-2)…(1). Write a program that will compute the factorial of a

number entered by the user.

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

The limits of int

(Note that in python 2.7 or later can handle this error by automatically changing the data type.)

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

Handling Large Numbers: Long Ints• Python provides a better solution for large, exact values in the form of a third

numeric type long int. • A long int is not a fixed size, but expands to accommodate whatever value it

holds. • To get a long int, you put an “L” suffix on a numeric literal.

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

Accumulating Results: Factorial• n!=n(n-1)(n-2)…(1). Write a program that will compute the factorial of a

number entered by the user.

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

Type Conversions

Note that the value is truncated, not rounded when using int() or long()

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

Computing with Strings

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

The String Data Type

• A string is a sequence of characters

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

The String Data Type

• A string is a sequence of characters

• Remember that the input statement treats whatever the user types as an expression to be evaluated

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

Indexing of the String

• A string is a sequence of characters

• Individual characters can be accessed through the operation of indexing. The general form for indexing is <string>[<expr>].

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

Slicing of the String• A string is a sequence of characters

• Access a contiguous sequence of characters or substring from a string is called slicing. The general form for slicing is <string>[<start>:<end>].

• Both start and end should be int-valued expressions. A slice produces the substring starting at the position given by start and running up to, but not including, position end.

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

The string data type is immutable

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

Operations for putting strings together• + concatenation

• * repetition

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

Summary of basic string operations

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

Example: single string processing

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

String RepresentationHow does a computer represent strings? •Each character is translated into a number, and the entire string is stored as a sequence of (binary) numbers in computer memory. •It doesn’t really matter what number is used to represent any given character as long as the computer is consistent about the encoding/decoding process.•One important standard , called ASCII, uses the numbers 0 through 127 to represent the characters typically found on a computer keyboard. For example, the capital letters A–Z are represented by the values 65–90, and the lowercase versions have codes 97–122.•UniCode is an extended standard to include characters of other written languages

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

The String Librarysplit - This function is used to split a string into a sequence of substrings. By default, it will split the string wherever a space occurs

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

The String Library

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

The eval() functioneval - This function takes any string and evaluates it as if it werea Python expression.

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

Converting Numbers to Strings

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

String Formatting

Notice that the final value is given as a fraction with only one decimal place. How to output something like $1.50 ?

You can do this by using the string formatting operator:

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

String Formatting

The string formatting operator is used like this:

<template-string> % (<values>)

•% signs inside the template-string mark “slots” into which the values are inserted. There must be exactly one slot for each value. Each of the slots is described by a format specifier that tells Python how the value for that slot should appear.•A formatting specifier has this general form:

%<width>.<precision><type-char>

type-char: decimal, float, or string width: how many spaces are used to display the value? If a

value requires more room than is given in width, Python will just expand the width so that the value fits.

precision: used with floating point values to indicate the desired number of digits after the decimal.

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

String Formatting

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

Multi-Line Strings

Special characters:

’\n’ - newline (as if you are typing <Enter> key on your keyboard’\t’ - <Tab>

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

File Processing

Three Key steps of file-processing in all programming languages:

1.Associate a file on disk with a variable in a program. This process is called opening a file. Once a file has been opened, it is manipulated through the variable we assign to it.

2.Define a set of operations that can manipulate the file variable. At the very least, this includes operations that allow us to read the information from a file and write new information to a file.

3.When we are finished with a file, it is closed. Closing a file makes sure that any bookkeeping that was necessary to maintain the correspondence between the file on disk and the file variable is finished up. (For example, if you write information to a file variable, the changes might not show up on the disk version until the file has been closed.)

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

File Processing: open a file

Associate a file on disk with a variable in a program. This process is called opening a file.

<filevar> = open(<name>, <mode>)

mode: “r” for read, “w” for write

Example:

infile = open(“numbers.data”,”r”)

Now we can use the variable inflie to read the contents of numbers.data from the disk.

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

File Processing: read

Once a file is open, Python provides three related operations for reading information from a file:•<filevar>.read()

– Returns the entire contents of the file as a single string. If the file contains more than one line of text, the resulting string has embedded newline characters between the lines

•<filevar>.readline()– read one line from a file (read all the characters up through the next newline

character); the string returned by readline will always end with a newline character

•<filevar>.readlines()o returns a sequence of strings representing the lines of the file

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

File Processing: read

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

File Processing: write

• Open a file for output:

Outfile = open(“mydata.out”, “w”)•A word of warning: if a file with the given name does exist, Python will delete it and create a new, empty file.

• Put data into a file using the write operation:

<file-var>.write(<string>)

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

Coming Attraction: Objects

• Notice the operations of the file processing are in the format of:– infile.read() – infile.close()

which are different from the normal function applications such as abs(x)

• In Python, a file is an example of an object. Objects combine both data and operations together. An object’s operations, called methods, are invoked using the dot notation.

• Notice that strings are also objects in Python. You can invoke methods of strings:

myString.split()

Is equivalent to

string.split(myString)