Lecture3 - University of California, Irvine
Download
Report
Transcript Lecture3 - University of California, Irvine
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.
• Homework assignment #2 will be posted online by
5pm Friday, which will be due Jan 16 (Thur) before
class.
Computing with Numbers
Numeric Data Types
Example output:
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.
Numeric Data Types
• Notice how operations on
floats produce floats, and
operations on ints produce
ints.
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 ax2+bx+c
=0
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.
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.
Input number to take factorial of, n
Compute factorial of n, fact
Output fact
• Basic strategy: do repeated multiplications, use an accumulator variable
+ a loop structure
Initialize the accumulator variable
Loop until final result is reached
update the value of accumulator variable
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
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:
>>>
[0,
>>>
[5,
>>>
[5,
range(10)
1, 2, 3, 4, 5, 6, 7, 8, 9]
range(5,10)
6, 7, 8, 9]
range(5,10,3)
8]
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.
The limits of int
(Note that in python 2.7 or later can handle this error by automatically
changing the data type.)
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.
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.
Type Conversions
Note that the value is truncated,
not rounded when using int() or
long()
Computing with Strings
The String Data Type
• A string is a sequence of characters
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
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>].
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.
The string data type is immutable
Operations for putting strings together
•
•
+ concatenation
* repetition
Summary of basic string operations
Example: single string processing
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
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
The String Library
The eval() function
eval - This function takes any string and evaluates it as if it were
a Python expression.
Converting Numbers to Strings
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:
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.
String Formatting
Multi-Line Strings
Special characters:
’\n’
’\t’
- newline (as if you are typing <Enter> key on your keyboard
- <Tab>
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.)
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.
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
File Processing: read
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>)
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)