1 / 62

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

tlopez
Download Presentation

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

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 5 Instructor: Xiaohui Xie University of California, Irvine

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

  3. Defining Functions

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

  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!

  6. Functions – simple example

  7. Parameters of a function

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

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

  10. Functions with return values Using return statement:

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

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

  13. Scope of variables If 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.

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

  15. Nested functions Scoping for nested functions work similarly:

  16. Nested functions

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

  18. Control Structures Part I: Decision structures

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

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

  21. Flowchart of the temperature conversion program with warning

  22. The temperature conversion program with warning decision structure

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

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

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

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

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

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

  29. Two-way decisions: example

  30. Two-way decisions: an example

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

  32. Control Structures Part 2: Loop Structures

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

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

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

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

  37. Indefinite loop example: computing the average of a series of numbers Another implementation:

  38. File Loops One 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.

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

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

  41. Post-Test Loop • Suppose 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 enters • a valid value. This process is called input validation. • Here is a simple algorithm: • repeat • get a number from the user • until number is >= 0

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

  43. Data Collections

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

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

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

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

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

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

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

More Related