讲义教程说明asrpt_第1页
讲义教程说明asrpt_第2页
讲义教程说明asrpt_第3页
讲义教程说明asrpt_第4页
讲义教程说明asrpt_第5页
已阅读5页,还剩32页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Lesson content:More on Data TypesMore on Operators and ExpressionsList comprehension Utility FunctionsWorkshop PreliminariesWorkshop 1: Practice Using a Few More Python BasicsList Comprehension and Utility Functions Control Flow: ExceptionsMore on Running Python and Other Common IssuesWorkshop 2: Wo

2、rking with ExceptionsLesson 1: More on the Python Core Language 3 hoursMore on Data Types (1/4)Type conversionThere are times when it is necessary to convert between data types. The data conversion types are summarized in the table. FunctionDescriptionint(x ,base)Convert x to an integerlong(x ,base)

3、Convert x to an long integerfloat(x)Convert x to a floating point numbercomplex(real ,imag)Convert x to a complex numberstr(x)Convert object x to a string representationrepr(x)Convert object x to an expression stringeval(str)Evaluate a string and return an objecttuple(s)Convert sequence s to a tuple

4、list(s)Convert sequence s to a listchr(x)Convert an integer to a characterunichr(x)Convert a single character to its integer valueord(x)Convert x to an integerhex(x), oct(x)Convert x to hexadecimal or octal stringMore on Data Types (2/4)eval(object), repr(object) are the most general conversion type

5、s For converting from a string eval() can be used as a general purpose function eval()is afunction which evaluates a string as though it were an expression and returns a result x = eval(4.9809) x4.9809 y = eval(1,2) y(1,2)repr() returns a string representation of the object and is written to be appr

6、oximately opposite of eval x = repr(4.9809) x4.9809Note: repr and eval have much more usage and functionality. Only a small subset is described here. More on Data Types (3/4)Type conversion exampleConverting between list and tuple sequencesUse the built-in Python functions called list() and tuple()

7、myTuple = 1, 2, 3 myList = list(myTuple) myList1, 2, 3More on Data Types (4/4)Sequence packing/unpacking Python automatically pairs items on both sides of an assignmentThe following are examples of sequence packing:The following are examples of sequence unpacking:The following are examples of sequen

8、ce packing and unpacking:The following assignment provides a method of swapping variable values without creating a temporary variable myTuple = 1, 2, 3myTuple(1,2,3) myList = 1, 2, 3 (x, y, z) = myTupley2 x, y, z = myList x, y, z = 1, 2, 3 x, y, z = 1, 2, 3 x, y = y, xMore on Operators and Expressio

9、ns (1/3)Boolean expressionsThe and, or, and not reserved keywords can be used to form Boolean expressions that behave as follows:OperatorDescription x or y If x is false, return y, else return x x and yIf x is false, return x , else return y not xIf x is false, return 1, else return 0More on Operato

10、rs and Expressions (2/3)Truth testingTrue: any nonzero number or nonempty object.1, 2.3, (1,2), xyzFalse: a zero number, empty object, or the None object.0, 0.0, ( ), , , , , , , NoneComparisons and equality tests return 1 or 0 1+2 2+3, 2+3 1+2 or 2+3 , 2+3 or 3+4(3, 5)These expressions are not eval

11、uatedMore on Operators and Expressions (3/3)Augmented assignmentPython includes an alternate form for writing some expressions called augmented assignments.Usually this shorter form will run faster because it has been optimizedThe following is a partial list of operators:OperationDescriptionx += yx

12、= x + yx -= yx = x yx *= yx = x * yx /= yx = x / yx *= yx = x * yx %= yx = x % yL = 1,2,3L = L + 4L.append(4)L += 4slowfast(creates new list with every addition operation)List Comprehension (1/2)List comprehensionThe syntax for list construction is as follows:expression for item1 in sequence1for ite

13、m2 in sequence2.for itemN in sequenceNif conditionalwhich is equivalent to the following:for item1 in sequence1: for item2 in sequence2:. for itemN in sequenceN:if conditional: expressionList Comprehension (2/2)Benefits of list comprehensionUsually results in shorter (but not necessarily more readab

14、le) code:a = -1, 1, -2, 2, -3, 3aMinus = m for m in a if m dir(_builtins_)ArithmeticError, AssertionError, AttributeError, DeprecationWarning, EOFError, Ellipsis, EnvironmentError, Exception, FloatingPointError, IOError, ImportError, IndentationError, IndexError, KeyError, KeyboardInterrupt, LookupE

15、rror, MemoryError, NameError, None, NotImplemented, NotImplementedError, OSError, OverflowError, RuntimeError, RuntimeWarning, StandardError, SyntaxError, SyntaxWarning, SystemError, SystemExit, TabError, TypeError, UnboundLocalError, UnicodeError, UserWarning, ValueError, Warning, WindowsError, Zer

16、oDivisionError, _debug_, _doc_, _import_, _name_, abs, apply, buffer, callable, chr, cmp, coerce, compile, complex, copyright, credits, delattr, dir, divmod, eval, execfile, exit, filter, float, getattr, globals, hasattr, hash, help, hex, id, input, int, intern, isinstance, issubclass, len, license,

17、 list, locals, long, map, max, min, oct, open, ord, pow, quWit, range, raw_input, reduce, reload, repr, round, setattr, slice, str, tuple, type, unichr, unicode, vars, xrange, zipUtility Functions (2/10)Lambda operatorPython supports the creation of anonymous functions (i.e. functions that are not b

18、ound to a name) at runtime, using a construct called lambdaSyntax: lambda args : expression Example: a = lambda x,y : x+y; print a(1,2) 3For use where a regular function is not allowed (lambda functions are expressions, def is a statement).It is a very powerful concept thats well integrated into Pyt

19、hon and is often used in conjunction with functional programming concepts likefilter(),map()andreduce() (discussed later)Utility Functions (3/10)Lambda operator examples def f (x): return x*2. print f(8)64 g = lambda x: x*2 print g(8)64 def make_incrementor (n): return lambda x: x + n f = make_incre

20、mentor(2) g = make_incrementor(6) print f(42), g(42)44 48 print make_incrementor(22)(33)55lambda can be used as a runtime function generatorUtility Functions (4/10)MapMap callsfunction for each of the sequences items and returns a list of the return values. For example, to compute some cubes: a = ra

21、nge(1,11) a 1,2,3,4,5,6,7,8,9,10 map(lambda x: x*x*x, a) 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000 aSin = map(math.sin,a) aSin0.8414709848078965, 0.90929742682568171, 0.14112000805986721, - 0.7568024953079282, -0.95892427466313845, -0.27941549819892586, 0.65698659871878906, 0.98935824662338179, 0.

22、41211848524175659, -0.54402111088936977 Utility Functions (5/10)Map (contd)More than one sequence may be passed; the function must then have as many arguments as there are sequences and is called with the corresponding item from each sequence.Multi-dimensional sequences can be passed. Operating func

23、tions can be made flexible to operate recursively on each element of the sequence.map(None, list1, list2)is a convenient way of turning a pair of lists into a list of pairs. For example: seq = range(8) map(None, seq, map(lambda x: x*x, seq) (0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36),

24、(7, 49) Utility Functions (6/10)FilterFilter returns a sequence consisting of those items from the sequence for whichfunction(item)is true. For example, to compute some primes: a = range(2,25)a2,3,4,5,6,7,8,9,10,11,1224 filter(lambda x: x%2 != 0 and x%3 != 0, a) 5, 7, 11, 13, 17, 19, 23 Utility Func

25、tions (7/10)ReduceReduce returns a single value constructed by calling the function on the first two items of the sequence, then on the result and the next item, and so on. For example, to compute the sum of the numbers 1 through 10: reduce(lambda x, y: x+y, range(1, 11) 55 Utility Functions (8/10)S

26、ets engineers = set(John, Jane, Jack, Janice) programmers = set(Jack, Sam, Susan, Janice) managers = set(Jane, Jack, Susan, Zack)union employees = engineers | programmers | managers #intersection engineering_management = engineers & managers #difference fulltime_management = managers - engineers - p

27、rogrammers #add element engineers.add(Marvin) # print engineers # doctest: +SKIPset(Jane, Marvin, Janice, John, Jack)Utility Functions (9/10) employees.issuperset(engineers) # superset testFalse employees.update(engineers) # update from another set employees.issuperset(engineers)True for group in en

28、gineers, programmers, managers, employees: # doctest: +SKIP. group.discard(Susan) # unconditionally remove element. print group.Set(Jane, Marvin, Janice, John, Jack)Set(Janice, Jack, Sam)Set(Jane, Zack, Jack)Set(Jack, Sam, Jane, Marvin, Janice, John, Zack)Utility Functions (10/10)The enumerate funct

29、ionenumerate is useful when you need to loop on the elements of a list and need to know the index as well.for i, x in enumerate(myList): print myList%d: %r % (i, x)IteratorsSome objects are their own iterators. The file object for examplef = open(c:temptextfile.txt)for line in f: print line:-1sum(se

30、q)Returns the sum of a sequence of numbersX=range(1,10,2)sum(s)ObjectivesWhen you complete this exercise you will be able to extract all the files necessary to complete the demonstrations and workshops associated with this courseWorkshop file setup (option 1: installation via plug-in)From the main m

31、enu bar, select Plug-insTools Install Courses.In the Install Courses dialog box:Specify the directory to which the files will be written.Chooses the course(s) for which the files will be extracted.Click OK.Workshop Preliminaries (1/2)5 minutesWorkshop file setup (option 2: manual installation)Find o

32、ut where the Abaqus release is installed by typingabqxxx whereamiwhere abqxxx is the name of the Abaqus execution procedure on your system. It can be defined to have a different name. For example, the command for the 6.131 release might be aliased to abq6131.This command will give the full path to t

33、he directory where Abaqus is installed, referred to here as abaqus_dir.Extract all the workshop files from the course tar file by typingUNIX: abqxxx perl abaqus_dir/samples/course_setup.plWindows NT:abqxxx perl abaqus_dirsamplescourse_setup.plThe script will install the files into the current workin

34、g directory. You will be asked to verify this and to choose which files you wish to install. Choose y for the appropriate lecture series when prompted. Once you have selected the lecture series, type q to skip the remaining lectures and to proceed with the installation of the chosen workshops.Worksh

35、op Preliminaries (2/2)5 minutesThe objectives of this workshop are to expose the user to more features of PythonWorkshop 1: Practice Using a Few More Python Basics60 minutesControl Flow: Exceptions (1/10)What is an exception ?An exception is a Python object that is used for handling unusual circumst

36、ances during the execution of a programE.g., execution of any illegal operation will raise an built-in Python exception. 1/0 Traceback (innermost last): File , line 1, in ? ZeroDivisionError: integer division or moduloExceptions provide the user with information about the cause of an error.The user

37、can optionally take remedial action and continue the execution of the program OR can exit gracefully.Allow an error to be located easily. Are more sophisticated and easier to use than return status codes (example error code 11).Control Flow: Exceptions (2/10)Python has many different built-in except

38、ion typesException, ArithmeticError, AssertionError, AttributeError, EOFError, EnvironmentError, FloatingPointError, IOError, ImportError, IndentationError, IndexError, KeyError, LookupError, MemoryError, NameError, NotImplementedError, OSError, OverflowError, ReferenceError, RuntimeError, StandardE

39、rror, SyntaxError, SystemError, TabError, TypeError, UnboundLocalError, UnicodeDecodeError, UnicodeEncodeError, UnicodeError, UnicodeTranslateError, ValueError, WindowsError, ZeroDivisionErrorAny illegal operation will automatically trigger a built in Python exceptionThe user can define his own exce

40、ption types (more on that later)Control Flow: Exceptions (3/10)Terminology and syntaxThe act of generating an exception is called “raising” or “throwing.”An illegal operation will raise an illegal operation: 1/0 Traceback (innermost last): File , line 1, in ? ZeroDivisionError: integer division or m

41、odulo Or exceptions can be raised explicitly: raise ZeroDivisionError(test test test) Traceback (most recent call last): File , line 1, in ? ZeroDivisionError: test test testControl Flow: Exceptions (4/10)Raising an exceptionSyntax for the raise statement:raise exceptionObjectraise exceptionObject(a

42、rgument)raise exceptionObject, argument raise exceptionObject, (arg, arg, arg.)exceptionObject above could be a built-in Python exception or a user-defined exception object.Control Flow: Exceptions (5/10)Catching and handling an exception (try-except-else)The act of identifying an exception is calle

43、d “catching.”The act of responding to an exception is called “handling.”Once they are caught and handled program execution will continue.The try-except-else syntax for exception catching and handling is as follows:try: body except catchType1, var1: handleCode1 except catchType2, var2: handleCode2.ex

44、cept: defaultHandleCodeelse: elseBody If an exception is raised, the except statements are executed sequentially. If a statement matches, then the handler is executed, extra information is assigned to optional var, and the program continues past the try block. If no matching except clause is found,

45、then the raised exception cannot be handled by the try statement, and the exception is thrown up the call chain.This statement will catch all types (generally not a good idea!)Executed only if no exceptions are raisedControl Flow: Exceptions (6/10)Catching and handling an exception (try-finally)The

46、try-finally syntax for exception catching and handling is always used to run a block of code, regardless of whether an exception was raised or not:try: Bodyfinally: onTheWayOutCodeThe special thing about exceptions is that they do not have to cause a program to halt. Control Flow: Exceptions (7/10)C

47、atching and handling an exception (contd)A summary of try statement clause formsClause FormDescription except:catch all exception types (not mended) except catchName:catch exception catchName only except catchName, value:catch exception catchName and its extra data except (catchName1, catchName2):ca

48、tch any of the listed exceptions else:execute if no exceptions are raised finally:execute alwaysControl Flow: Exceptions (8/10)Rules of thumb for using exceptionsPut file calls and socket calls in a try-finally block. For example:f = open(filename, r)try: somethingfinally: f.close()Wrap function cal

49、ls in try statements instead of embedding exceptions within the functions. This will subvert the default program termination.try: some_func()except: import sys print exception caught, sys.exc_info()Control Flow: Exceptions (9/10)User-defined class exceptionExceptions may also be defined as classes a

50、nd class instances. For example:class MyError(Exception): passdef test(): raise MyError, *oops* try: test() except MyError, extra:. import sys. exc_type, exc_val = sys.exc_info():2. print Situation: %s: %s%(exc_type, exc_val). print extra:, extra. print exc_info:, sys.exc_info():2Situation: _main_.M

51、yError: *oops*extra: *oops*exc_info: (, )We will discuss class objects in detail later.All exceptions must be derived from this base objectControl Flow: Exceptions (10/10)sys.exc_info() : Gives detailed information about exception being handled. try: 1/0except ZeroDivisionError, var: print n,15*,nEx

52、tra information =,var import sys for item in sys.exc_info(): print * Exception information =,item for attr in dir(item): print , print attr, -, getattr(item,attr)* Extra information = integer division or modulo by zero* Exception information = exceptions.ZeroDivisionError _doc_ - Second argument to

53、a division or modulo operation was zero. _module_ - exceptions* Exception information = integer division or modulo by zero args - (integer division or modulo by zero,)* Exception information = tb_frame - tb_lasti - 18 tb_lineno - 2 tb_next - NoneThis behavior is part of the introspection API in Pyth

54、onTypeTraceback objectDescriptionMore on Running Python (1/3)Python on WindowsLater versions of Windows know how to run .py files directly from the command line or when double-clicked even if the PATH environment variable does not specify where Python.exe has been installedExample: D: print_test.py testThe .py extension may be avoided on the command line by making Python appear like a .exe, , or .bat file. To do this, use the PATHEXT Windows environment variableExample: D: set PATHEXT=%PATHEXT%;.py D: pr

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论