Содержание
- 2. About Python
- 3. What is Python? A programming language Open Source Free; source code available Download on your own
- 4. Features of Python A script language Interpreted No compile/link stage Write and run Slow compared to
- 5. The Zen of Python Beautiful is better than ugly. Explicit is better than implicit. Simple is
- 6. Part 1: Variables and built-in types
- 7. Basic data types
- 8. Useful functions type(object) – returns type of an object dir(object) – returns a list of attributes
- 9. Useful functions help(object) – returns description of an object >>> help(int) class int(object) | int(x=0) ->
- 10. Numeric types and literals
- 11. Numeric tools Expression operators: +, -, *, /, >>, **, &, etc. >>> 2 + 3
- 12. Built-in mathematical functions: pow, abs, round, int, hex, oct, bin, etc. Numeric tools >>> pow(2, 19)
- 13. Numeric tools Utility modules random, math, etc. >>> import math >>> math.pi 3.141592653589793 >>> math.factorial(10) 3628800
- 14. Type mixing Besides mixing operators in expressions we can also mix numeric types Python ranks the
- 15. Division True division – operator / In Python 3.x operator / performs true division, always keeping
- 16. String String An ordered collection of characters used to store and represent text-based information.
- 17. Escape sequences Backslashes are used to introduce special character codings known as escape sequences. Escape sequences
- 18. Basic operations Function len, concatenation, repetition and operation in >>> len(‘abc’) # Length: number of items
- 19. Indexing and Slicing Indexing let us to get a single character (returned as single character string)
- 20. Conversions One of Python design mottos is it refuses the temptation to guess. As a prime
- 21. String methods >>> ‘BIG’.lower() 'big’ >>> ‘small’.upper() 'SMALL’ >>> ‘SMALL AnD big’.swapcase() 'small aNd BIG’ >>>
- 22. Lists Ordered collections of arbitrary objects Lists are just places to collect other objects which maintain
- 23. List creation
- 24. Basic operations >>> len([1,2,3,4]) # Length: number of items 4 >>> list(‘abc’) + list(‘def’) # Concatenation:
- 25. Changes List are mutable, so we can change them without creating new lists using some operators
- 26. >>> a = [1, 2, 3, 4, 5, 4] >>> a.remove(4) # Removes the first occurrence
- 27. Lists sorting >>> a = ['abc’, 1, 0.99] >>> a.sort() Traceback (most recent call last): File
- 28. Other methods >>> a = [1, 2, 3, 4] >>> a.reverse() # Reverse order >>> a
- 29. List comprehensions Python supports a concept called list comprehensions. It can be used to construct lists
- 30. List comprehensions >>> test = [21, 1, 9123, 323, 112] >>> [x for x in test
- 31. Tuple Tuples work exactly like lists, except that tuples can’t be changed in place (they are
- 32. Tuple creation
- 33. Basic operations Function len, concatenation, repetition, operation in, slicing >>> len((1,2,3,4)) # Length: number of items
- 34. >>> a = (1, 2, 3, 4, 3, 2, 1) >>> a.index(3) # We already know
- 35. Dictionaries In dictionaries, items are stored and fetched by a key, instead of by positional offset.
- 36. Dicts creation
- 37. Basic operations Indexing, function len, membership operator, getting keys/values >>> d = {‘spam’:2, ‘eggs’: 3, ‘ham’:
- 38. In-place changes >>> d = {‘spam’:2, ‘eggs’: 3, ‘ham’: 1} # Create a simple dict >>>
- 39. Other dict methods >>> d = {‘spam’:2, ‘eggs’: 3, ‘ham’: 1} # Create a simple dict
- 40. Other dict methods >>> d.pop(‘muffin’) # Delete and return object 5 >>> d.pop(‘strange key’) # Operating
- 41. Dict comprehensions >>> d = { x: x**2 for x in (2, 4, 6)} # Dict
- 42. Sets A set is an unordered collection with no duplicate elements. Basic uses include membership testing
- 43. Basic operations Function len, fast membership testing, equality test >>> basket = {'apple', 'orange', 'apple', 'pear',
- 44. Set operations >>> a = set('abracadabra') >>> b = set('alacazam') >>> a - b # letters
- 45. Set methods In place change methods, set comprehensions >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange’}
- 46. Files File objects are Python code’s main interface to external files on your computer. Files are
- 47. Files It is good practice to use the with keyword when dealing with file objects. The
- 48. Boolean Python today has an explicit Boolean data type called bool, with the values True and
- 49. NoneType The sole value of the type NoneType is None. None is frequently used to represent
- 50. Interview Reverse the number using list Reverse the number using string Reverse the number using only
- 51. Assignment Statement Forms
- 52. Dicts creation
- 53. Dicts creation
- 54. Dicts creation
- 55. Boolean expressions ‘True’ and ‘ False’ are predefined values; actually integers 1 and 0 Value 0
- 56. String Single quotes or double quotes can be used for string literals Produces exactly the same
- 57. String conversions Convert data types using functions ‘str’, ‘int’, ‘float’ ‘repr’ is a variant of ‘str’
- 58. String operations Common string operations on page 75 in ‘Learning Python’
- 59. Changing strings. Not! A string cannot be changed in Python! Immutable Good reasons for this; more
- 60. String methods Strings have a set of built-in methods No method ever changes the original string!
- 61. List Ordered collection of objects; array Heterogenous; may contain mix of objects of any type
- 62. List operations Lists are mutable; can be changed in-place Lists are dynamic; size may be changed
- 63. List methods, part 1 Lists have a set of built-in methods Some methods change the list
- 64. List methods, part 2 Use the built-in 'sort' method: efficient The list is sorted in-place; a
- 65. Objects, names and references All values are objects A variable is a name referencing an object
- 66. Dictionary An unordered collection of key/value pairs Each key maps to a value Also called "mapping",
- 67. Forgetting things: garbage collection What happens to the object when its name is ’del’ed, or reassigned
- 68. Dictionary methods, part 1
- 69. Dictionary methods, part 2
- 70. Tuple Same as list, except immutable Once created, can't be changed Some functions return tuples
- 71. String formatting Tuples are used as operands in string formatting when >1 items The length of
- 72. Part 2: Statements
- 73. 'if' statement; block structure The Python feature that one either loves or hates Block structure is
- 74. Dictionary often better than if… elif… Particularly with many hardcoded choices (elif's)… More compact, and more
- 75. Built-in types and their Boolean interpretations
- 76. 'for' statement Repetition of a block of statements Iterate through a sequence (list, tuple, string, iterator)
- 77. Built-in functions 'range' and 'xrange' Built-in functions 'range' and 'xrange' useful with 'for' 'range' creates a
- 78. 'while' statement Repetition of a block of statements Loop until test becomes false, or 'break'
- 79. Optional 'else' block in loops 'else' block executed if no 'break' encountered May often replace success/failure
- 80. Error handling: ’try’ and ’except’ Run-time error normally causes execution to bomb The error message gives
- 81. How to split up long lines Sometimes a source code line needs splitting up Indentation rule
- 82. Statements not covered in this course 'finally': used with 'try', 'except' 'raise': causes an exception 'yield':
- 83. Part 3: Functions
- 84. How to define your own function Use the 'def' statement Function body follows; indented! This is
- 85. Function features The value of an argument is not checked for type Often very useful; overloading
- 86. Function arguments: fixed Fixed number of arguments Associated by order
- 87. Function arguments: variable List of any number of arguments Useful when unknown number of arguments needed
- 88. Function arguments: default values Arguments may have default values When argument not given in a call,
- 89. Function arguments: keywords Keyword/value arguments The argument values collected into a dictionary Called 'kwargs', by convention
- 90. Function arguments: local variables Arguments become local variables Immutable values are copied, in effect Mutable values
- 91. Function without 'return': value None A function does not have to use the 'return' statement If
- 92. The 'math' module: functions and constants A peek at modules Math functions available in a separate
- 93. Functions are objects; names are references A function is just another kind of object Nothing magical
- 94. Built-in function 'map' Built-in function that works on a list 'map' takes a function and a
- 95. Built-in function 'reduce'
- 96. Built-in function 'filter'
- 97. Files: reading A file object is created by the built-in function 'open' The file object has
- 98. Files: writing The 'write' method simply outputs the given string The string does not have to
- 99. Part 4: Modules
- 100. Example: Reverse complement NT sequence Given a nucleotide sequence, produce reverse complement Use available features
- 101. Make a module of the code How to make the code even more reusable? Step 2:
- 102. How to use the module: ’import’ statement The ’import’ statement makes a module available The module
- 103. Module self-test code: the ’__name__’ trick The ’import’ statement executes all code in the module file
- 104. Now, the ’import’ statement behaves
- 105. Modules are easy, fun, and powerful The module feature is the basis for Python's ability to
- 106. Namespaces A namespace is a bag of names A module is a namespace Use the built-in
- 107. Avoiding clutter in your namespace Using ’from module import *’ can create clutter Fine-tuning of import;
- 108. Doc strings: ’__doc__’ We have mentioned documentation strings before The first string in a module The
- 109. Part 5: Object-oriented programming, classes
- 110. Classes vs. objects (instances) A class is like a Prototype Blue-print ("ritning") An object creator A
- 111. A class example: Geometrical shapes Let's define classes for geometrical shapes With data; position, etc With
- 112. Instances of classes Let's create some instances of the Circle class Look at attribute 'radius' Use
- 113. Changing an instance: references Variables may reference the same object Changing an attribute changes the object,
- 114. Changing an instance: attribute add/delete An attribute can be added! And deleted!
- 115. Equality between objects Two kinds of equality: Are the two objects similar in value? Are the
- 116. Special methods in classes Special methods '__xxx__' in classes Define custom-made behaviour See page 327 in
- 117. Using the special methods, part 1 Special method definitions are detected by Python Built-in functions use
- 118. Using the special methods, part 2 Defining special methods may clarify code tremendously But: Stay reasonable
- 119. Inheritance: Class hierarchies Let's define a general 'Shape' class 'Circle' is a special case of 'Shape'
- 120. Instances of classes using inheritance Which method is called by which instance? Polymorphism Selection of method
- 121. Part 6: Standard library modules
- 122. Module 're', part 1 Define a pattern The pattern syntax is very much like Perl or
- 123. Module 'sys', part 1 sys.argv List of command-line arguments; sys.argv[0] is script name sys.path List of
- 124. Module 'sys', part 2 sys.stdout, sys.stdin, sys.stderr Predefined file objects for input/output 'print' stuff goes to
- 125. Module 'os', part 1 os.getcwd() Returns the current directory
- 126. Module 'os', part 2 os.chdir(path) Changes the current working directory to 'path' os.listdir(path) Return a list
- 127. os.system(command) Execute the shell command (string) in a subprocess Return the error code as integer os.popen(command,
- 128. Module 'os.path', part 1 os.path.abspath(path) Returns the absolute path for the given relative 'path'
- 129. Module 'os.path', part 2 os.path.join(path, path, …) Joint together the path parts intelligently into a valid
- 130. Module 'os.path', part 3 os.path.isfile(path) Is 'path' the name of a file? os.path.isdir(path) Is 'path' the
- 132. Скачать презентацию