Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "CS190/295 Programming in Python for Life Sciences: Lecture 3 Instructor: Xiaohui Xie University of California, Irvine."— Presentation transcript:

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

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

3 Computing with Numbers

4 Numeric Data Types Example output:

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

6 Numeric Data Types Notice how operations on floats produce floats, and operations on ints produce ints.

7 Using the Math Library Python 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 ax 2 +bx+c =0

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

9 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, n Compute factorial of n, fact Output fact Initialize the accumulator variable Loop until final result is reached update the value of accumulator variable

10 Accumulating Results: Factorial Initialize the accumulator variable Loop until final result is reached update 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

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

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

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

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

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

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

17 Computing with Strings

18 The String Data Type A string is a sequence of characters

19 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

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

21 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 [ : ]. 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.

22 The string data type is immutable

23 Operations for putting strings together + concatenation * repetition

24 Summary of basic string operations

25 Example: single string processing

26 String Representation How 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

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

28 The String Library

29 The eval() function eval - This function takes any string and evaluates it as if it were a Python expression.

30 Converting Numbers to Strings

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

32 String Formatting The string formatting operator is used like this: % ( ) % 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: %.  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.

33 String Formatting

34 Multi-Line Strings Special characters: ’\n’ - newline (as if you are typing key on your keyboard ’\t’ -

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

36 File Processing: open a file Associate a file on disk with a variable in a program. This process is called opening a file. = open(, ) 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.

37 File Processing: read Once a file is open, Python provides three related operations for reading information from a file:.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.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.readlines() o returns a sequence of strings representing the lines of the file

38 File Processing: read

39 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:.write( )

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


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

Similar presentations


Ads by Google