1 / 79

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

This lecture covers the basics of working with strings in Python, including indexing, slicing, concatenation, and string representation. It also introduces file processing, including opening files, reading and writing file contents.

Download Presentation

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

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Announcements • Homework assignment #2 is out, due on Jan 31 (Tue) before class • Jake will lead a lab session this Thursday (Jan 26). Bring your laptop.

  3. Computing with Strings

  4. The String Data Type • A string is a sequence of characters

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

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

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

  8. The string data type is immutable

  9. Operations for putting strings together • + concatenation • * repetition

  10. Summary of basic string operations

  11. Example: single string processing

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

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

  14. The String Library

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

  16. Converting Numbers to Strings

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

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

  19. String Formatting

  20. Multi-Line Strings Special characters: ’\n’ - newline (as if you are typing <Enter> key on your keyboard ’\t’ - <Tab>

  21. File Processing Three Key steps of file-processing in all programming languages: • Associate a file on disk with a variable in a program. This process is called openinga file. Once a file has been opened, it is manipulated through the variable we assign to it. • 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. • 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.)

  22. File Processing: open a file Associate a file on disk with a variable in a program. This process is called openinga 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.

  23. 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() • returns a sequence of strings representing the lines of the file

  24. File Processing: read

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

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

  27. Defining Functions

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

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

  30. Functions – simple example

  31. Parameters of a function

  32. Functions and Parameters • 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 def <name>(<formal-parameter-1>,…,<formal-parameter-n>) <name>(<actual-parameter-1>,…,<actual-parameter-n>)

  33. When a function is called When Python comes to a function call, it initiates a four-step process. • The calling program suspends at the point of the call. • The formal parameters of the function get assigned the values supplied by the actual parameters in the call. • The body of the function is executed. • Control returns to the point just after where the function was called.

  34. Functions with return values Using return statement:

  35. Functions can return more than one value When calling this function, place it in a simultaneous statement:

  36. Control Structures Part I: Decision structures

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

  38. An example: temperature warning Suppose now we want to enhance the program by providing temperature warning like this:

  39. Flowchart of the temperature conversion program with warning

  40. The temperature conversion program with warning decision structure

  41. Simple if-statement Control flow of simple if-statement:

  42. 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”).

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

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

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

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

  47. Two-way decisions: example

  48. Two-way decisions: an example

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

  50. Control Structures Part 2: Loop Structures

More Related