Äîêóìåíò âçÿò èç êýøà ïîèñêîâîé ìàøèíû. Àäðåñ îðèãèíàëüíîãî äîêóìåíòà : http://www.stsci.edu/hst/training/events/Python/class2.pdf
Äàòà èçìåíåíèÿ: Wed Jun 15 23:13:19 2005
Äàòà èíäåêñèðîâàíèÿ: Sun Dec 23 00:36:53 2007
Êîäèðîâêà:
STSCI Python Introduction
Class 2 Jim Hare

Class URL www.pst.stsci.edu/~hare
· · · · · Each Class Presentation Homework suggestions Example files to download Links to sites by each class and in general I will try to have the PowerPoint slides by Friday AM before each Monday's class.

1


Today's Agenda
· · · · · · · Object Oriented Concepts Built-in Types Operators Formatting to Strings Control Flow Functions Passing Arguments to Modules

Object Oriented Concepts
· Every piece of data stored in a program is an object. · Each object has an identity, a type, and a value. · When an object is created, the object created is called an instance of that type.

2


Object Identity
­ Identity ­ pointer or reference to the location in memory. >>> a = 42 # create an instance of an integer a >>> id(a) # gets the memory location for object a 13074924

Object Type
· The type of an object describes the internal representation of the object, the methods and operations that it supports. · Having the data, methods and operations defined within an object is call encapsulation. · This is what is different from old programming techniques. You don't have to know how the object is implemented. You just need to know the interface.

3


Example of type()
>>> nameString = "Zach Hare" >>> type(nameString) >>> nameList = ['Zach','Hare'] >>> type(nameList) >>> nameDict = {'first':'Zach','last':'Hare'};type(nameDict) >>> age = 12;type(age)

Object Methods and Attributes
· A method is a function that performs some sort of operation on an object when the method is invoked. · An attribute is a property or value associated with an object. · Attributes and methods are accessed using the dot (.) operator.

4


Example of Methods and Attributes
>>> >>> >>> 3.0 >>> >>> a = 3 +4j r = a.real print r # Create a complex number # Get real part (an attribute)

b = [1,2,3] b.append(7) # add element 7 to the list with # method append >>> b [1, 2, 3, 7]

Built-in Types
· · · · None Type Numeric Types Sequence Types Mapping Types

5


The None Type
· The None type denotes a null object. · None has no attributes and evaluates to false in Boolean expressions. · Often used as a default value in optional arguments. X = None

Numeric Types
· Integers - whole numbers from -2147483647 to 2147483647 in 32 bits, 4 bytes. Some machines the range is larger 8 bytes. · Long integers ­ whole numbers limited only by available memory. · Floating-point ­ uses machines double-precision 64-bit, 8 bytes. · Complex numbers ­ a pair of floating-point numbers. Z has Z.real and Z.imag.

6


Operators and the Order of Evaluation
Operator (...), [... ], {... } `...' s[i], s[i:j], s.attr f(...) +x, -x, ~x x**y x * y, x / y, x % y x + y, x ­ y x << y, x >>y x&y x^ y Name Tuple, list, dictionary creation String conversion Indexing and slicing attributes Function calls Unary operators Power(right associative) Multiplication, division, modulo Addition, subtraction Bit shifting Bitwise and Bitwise exclusive or

Operators and the Order of Evaluation
Operator
x|y x x x x x x < y, x <= y, > y, x >= y, == y, x != y <>y is y, x is not y in s, x not in s

Name
Bitwise or Comparison, identity, and sequence membership tests

not x x and y x or y lambda args: expr

Logical negation Logical and Logical or Anonymous function

7


Operator Precedence Examples
>>> x = 2;y=3 >>> z = x + y**2 % 6 >>> z 5 >>>z =x +((y**2) % 6)

Sequence Types
· Sequences represent ordered sets of objects indexed by non-negative integers and include strings, Unicode strings, lists, tuples, xrange objects, and buffer objects. · Strings and buffers are sequences of characters. · xrange objects are sequences of integers. · Lists and tuples are sequences of arbitrary objects.

8


List Type Example
>>> xList = [[0,1,2], [3,4,5], [6,7,8]] >>> xList [0][0] 0>>> xList [0][2] 2>>> xList [2][1] 7 X[row][column]

String Splicing
>>> xString = 'I am learning NNNNNN today` >>> xString[14:20] = 'Python` Traceback (innermost last): File " ", line 1, in ? TypeError: object doesn't support slice assignment >>> xString = xString[:14] + 'Python' + \ xString[20:] >>> xString 'I am learning Python today'

9


Mapping Types
· A mapping object represents an arbitrary collection of objects that are indexed by another collection of nearly arbitrary key values. · Mapping objects are unordered and keys are immutable. The mappings are mutable. · Dictionaries are the only built-in mapping type.

Formatting to Strings
· X = "Python" · Y = "I am learning %s today" % X · X = 3.146789 · Y = "The real number is %-10.4f" % X · The real number is 3.1468

10


String Formatting Conversions
Char Format
d,i o X

Char Format

Decimal integer of L u Unsigned integer or L Octal integer or L x Hexadecimal integer or L Hexadecimal integer f Floating Point [-]m.dddddd Uppercase letters. e [-]m.dddddde+xx E [-]m.ddddddE+xx G,g Use %E or %e for exponents less than ­4 or greater than the precison; otherwise use %f s String or any object. The formatting code use str() to generate strings. r Same string as repr() c Single character % Literal %

String Formatting Examples
a = 42 b = 13.142783 c = "hello" d = {`x':13, `y':1.54321, `z':'world'} `a is %d' % a #"a is 42" `%10d %f' % (a,b) # " 42 13.142783" `%(x)-10d %(y)0.3g' %d #"13 1.54" `%*.*f' % (5,3,b) # "13.143"

11


Control Flow
· Supports if, for, while, and try · Blocks of code executed within a control flow are indented. · It is a syntax error when indentation is not correct · Boolean expressions "or", "and", and "not" are used for Truth Values · pass # do nothing

Control Flow Conditionals
if expression: statements elif expression: statements elif expression: statements else: statements #endif Note: You don't need this but it is wise to keep you organized sometimes.

12


Loops while
while expression: statements if expression: break else: statements

Loops For
for i in range(0,10,2): # ie.(start,stop,step) statements if Istring[I] == `foo': break else: statements #endfor not necessary

13


range() and xrange()
· range(start,end,stride) · range constructs a list and populates values according to start, end and stride(step size). · Remember end is an up to value · xrange() ­ value calculated when accessed; it save memory A = range(5) # A = [0,1,2,3,4] D = range(8,2,-2) # D = [8,6,4] b = xrange(1000000) # b = [0,1,2, ..., 999999]

Try and Except Control
· Try and Except blocks are a way to override python stopping the execution of a program due to a system error. · The except block provides a way to execute statements on a specific error or set of errors · Except blocks without a specified type of error execute the statements for any error.

14


Try and Except Block
try: statements except: statements to handle error #could just use pass

Except: Error Types
try: ... except IOError, e: # e is optional args of # raise ... except TypeError: · See Appendix A, "The Python Library" for details of exception errors

15


Passing Arguments to Modules
· Using the python module sys
­ import sys ­ sys.argv ­ a list containg the module name in sys.argv[0] followed by arguments passed ­ sys.path ­ path used to find modules, uses PYTHONPATH environment variable

Passing Arguments to Modules os module
· os.environ ­ is a dictionary of the current environment variables
­ print os.environ[`DSQUERY']

nomad
­ os.environ[`DSQUERY'] = "R2D2" Note: This will only change the environment variable for your current program run

· Example /ess5/psdpython/dbtools.py

16


os.system
· os.system(`pwd') · os.system(`echo $DSQUERY') · The shell is the basic c shell not tcsh.

Mail Example
import os toList = [{`name':'Paul', 'email':'plee@stsci.edu'}, {`name':'Erin','email':'roye@stsci.edu}] for toDict in toList: mailString = """Hi %s, The Python class is today at 11:30. Jim""" % toDict[`name'] os.system("printf `%s' | mailx ­s `Class Today' " " ­r hare@stsci.edu %s " %(mailString,toDict[`email'])

17


Functions
· Function template · Consists of def statement, parameters and return def test1(x,y,j=`testcase1') j=`testcase1' is the default · Example /ess5/psdpython/pythonclass/class2/update_ default_db.py

Passing Arguments ­ if __name__==`__main__':
if __name__ == '__main__': if len(sys.argv) != 3: print " Error in arguments try again." sys.exit() database = string.lower(sys.argv[1]) account = sys.argv[2] run(database,account)

18


Passing Arguments - continued
· __main__ is the name of the originating or first module run in the current execution of python def run(database, #database account='sogsspss'): #account os.system('printf "sp_defaultdb %s,%s\\ngo" | isql' % (account,database)) os.system('printf "select db_name()\\ngo" | isql') return None

Functions Returning Values
def splitonperiod(inString): # is a string import string stringList = string.split(inString,'.') ... test = 1 return test,stringList aString = "md.summer.2002.STSCI.EDU" status,varList = splitonperiod(aString)

19


Raw Input Command
first = raw_input(`Type your first name: `) mid = raw_input(`Type your middle name: `) last = raw_input(`Type your last name: `) print "Your full name is %s %s %s" \ % (first,mid,last) · Example: myName.py

Files
· myFile = open(`build_id.data','r') · File modes are: `r', `w', or "a". `b' following means binary ie. `rb' · Updates `r+' or `w+', can perform both input and output, as long as output operations flush their data before subsequent input operations ie. f.flush()

20


File Methods - Read
· F.read - Reads at most n bytes · F.readline() - Reads a single line of input · F.readlines() - Reads all the lines and returns a list. Ie. myList = F.readlines()

File Methods - Write
· F.write(S) · F.writelines(L) - Writes string S - Writes all strings in List L

21


File Methods
· F.close() - closes the file F · F.tell() - returns the file pointer · F.seek(offset [,where]) ­ seek to new file position · F.isatty() - 1 if F is interactive terminal · F.flush() - Flushes output buffers · F.truncate([size]) - truncates to size bytes · F.fileno() - integer descriptor

File Attributes
· F.closed - Boolean 0 = open, 1=closed · F.mode - I/O mode of file · F.name - name of file or source · F.softspace - indicator of whether a space character needs to be printed before another value when using the print statement.

22


Standard Input, Output, and Error
· import sys - to get access to Standard I/O files · sys.stdin - Standard Input · sys.stdout - Standard Output · sys.stderr - Standard Error

Examples and Homework
· Look at:
­ osEnv.py ­ a module to create environment variable setup scripts for regression tests. ­ osReg.py ­ a module to run a test in two different environments and compare results. ­ Download these to your working directory. ­ From python import osEnv ­ osEnv.makeEnvFile(`test1') ­ Get out of python and look at envtest1.py that you just generated

23