CS190/295 Programming in Python for Life Sciences: Lecture 2 Instructor: Xiaohui Xie University of...

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

Transcript of CS190/295 Programming in Python for Life Sciences: Lecture 2 Instructor: Xiaohui Xie University of...

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

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

Instructor: Xiaohui Xie

University of California, Irvine

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

Announcements

• Classroom for this course will be moved to DBH 1500 starting from Jan 17 (next Tuesday).

• Enrollment max cap has been increased to 35 for CS295. However, due to limited resource, the enrollment cap cannot be further increased.

• First homework assignment will be out before 5pm, Friday. Please check the course website.

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

Review of the last lecture

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

CPU (central processing unit) - the “brain” of the machine, where all the basic operations are carried out, such as adding two numbers or do logical operations

Main Memory – stores programs & data. CPU can ONLY directly access info stored in the main memory, called RAM (Random Access Memory). Main memory is fast, but volatile.

Secondary Memory – provides more permanent storageo Hard disk (magnetic)o Optical discso Flash drives

Input Devices – keyboard, mouse, etc Output Device – monitor, printer, etc

Hardware Basics

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

Python is an interpreted language

• >>> is a Python prompt indicating that the interpreter is waiting for us to give a command. A complete command is called a statement

• Start the Python interpreter in an interactive mode

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

Inside a Python program

• comments: o any text from # through the end of a line o intended for humans, ignored by the Python

• defining a function called main• x is variable, used to give a name to a value so that we can refer to later• The statement starting with for is an example of a loop

o A loop is a device that tells Python to do the same thing over and over again

o The lines indented underneath the loop heading form the body of the loop• x = 3.9 * x * (1-x) is an assignment statement: the value on the

right-hand side is computed, and is then stored back (assigned) into the variable on the left-and side of =.

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

Topic 2: Writing Simple Programs

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

Software development process

• Formulate Requirements Figure out exactly what the problem to be solved is

• Determine Specifications Describe exactly what your program will do. What will it accomplish? What the inputs and outputs of the program?

• Create a Design Formulate the overall structure of the program. How will the program achieve the desired goals?

• Implement the Design Translate the design into a computer language and put it into the computer.

• Test/Debug the Program Try out your program and see if it works as expected. If there are any errors (often called bugs), then you should go back and fix them. The process of locating and fixing errors is called debugging a program.

• Maintain the Program Continue developing the program in response to the needs of your users. Most programs are never really finished; they keep evolving over years of use.

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

An example: temperature converter

• Input the temperature in degrees Celsius (call it celsius)

• Calculate fahrenheit = 9/5 * celsius + 32

• Output fahrenheit

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

Elements of Programs: Names

• Names (also called identifiers): we give names to

– modules (e.g., convert, chaos)

– functions within modules (e.g., main)

– variables (e.g., celsius, fahrenheit)

• Python rules on identifiers

– must begin with a letter or underscore (‘_’), which may be followed by any sequence of letters, digits, or underscores.

– cannot contain any spaces

– the names that are part of Python, called reserved words, cannot be used as ordinary identifiers

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

Elements of Programs: Expressions

• Programs manipulate data. The fragments of code that produce or calculate new data values are called expressions.

• Using a variable that has not been assigned a value will result in a NameError.

• More complex expressions can be constructed by combining simpler expressions with operators (e.g., +, -, *, /, **)

• Spaces are irrelevant within an expression. Usually it’s a good idea to place some spaces in expressions to make them easier to read

• Use parentheses to modify the order of evaluation.

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

Output statementsThe syntax of print:

•These are templates for using print, using notations called meta-languages

•A print statement consists of the keyword print followed by zero or more expressions, which are separated by commas.

•The angle bracket notation (<>) is used to indicate “slots” that are filled in by other fragments of Python code. The name inside the brackets indicate what is missing; expr stands for an expression.

•The ellipses (“...”) indicate an indefinite series (of expressions, in this case). You don’t actually type the dots.

•The fourth version shows that a print statement may be optionally ended with a comma.

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

Output statementsThe semantics of print:

•Displays information in textual form, with expression evaluated left to right

•The resulting values are displayed on a single line in a left to right fashion

•A single blank space character is placed between the displayed values

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

Assignment statements: simple assignment

• The template for the basic assignment statement:

<variable> = <expr>

where variable is an identifier and expr is an expression

• A variable can be assigned many times. It always retain the value of the most recent assignment.

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

Assignment statements: assigning input

• The template for the assigning input:

<variable> = input(<prompt>)

where prompt is an expression that serves to prompt the user for input; this is almost always a string literal (i.e., some text inside of quotation marks).

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

Assignment statements: Simultaneous Assignment

• The template for simultaneous assignment:

<var>, <var>, …, <var> = <expr>, <expr>, …, <expr>• Python evaluate all the expressions on the right-hand side and then assign

these values to the corresponding variables named on the left-hand side.

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

Definite Loops• Programmers use loops to execute a sequence of statements several times in succession.

The simplest kind of loop is called a definite loop. This is a loop that will execute a definite number of times

• A Python for loop has this general form:

– The body of the loop can be any sequence of Python statements. The start and end of the body is indicated by its indentation under the loop heading

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

Topic 3: Computing with Numbers

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

Numeric Data Types

Example output:

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

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 21: CS190/295 Programming in Python for Life Sciences: Lecture 2 Instructor: Xiaohui Xie University of California, Irvine.

Numeric Data Types

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

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

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 23: CS190/295 Programming in Python for Life Sciences: Lecture 2 Instructor: Xiaohui Xie University of California, Irvine.

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 24: CS190/295 Programming in Python for Life Sciences: Lecture 2 Instructor: Xiaohui Xie University of California, Irvine.

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 25: CS190/295 Programming in Python for Life Sciences: Lecture 2 Instructor: Xiaohui Xie University of California, Irvine.

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 26: CS190/295 Programming in Python for Life Sciences: Lecture 2 Instructor: Xiaohui Xie University of California, Irvine.

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 27: CS190/295 Programming in Python for Life Sciences: Lecture 2 Instructor: Xiaohui Xie University of California, Irvine.

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 28: CS190/295 Programming in Python for Life Sciences: Lecture 2 Instructor: Xiaohui Xie University of California, Irvine.

The limits of int

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

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 30: CS190/295 Programming in Python for Life Sciences: Lecture 2 Instructor: Xiaohui Xie University of California, Irvine.

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 31: CS190/295 Programming in Python for Life Sciences: Lecture 2 Instructor: Xiaohui Xie University of California, Irvine.

Type Conversions

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