Python Language
Total Page:16
File Type:pdf, Size:1020Kb
Python Language #python Table of Contents About 1 Chapter 1: Getting started with Python Language 2 Remarks 2 Versions 3 Python 3.x 3 Python 2.x 3 Examples 4 Getting Started 4 Verify if Python is installed 4 Hello, World in Python using IDLE 5 Hello World Python file 5 Launch an interactive Python shell 6 Other Online Shells 7 Run commands as a string 7 Shells and Beyond 8 Creating variables and assigning values 8 User Input 12 IDLE - Python GUI 13 Troubleshooting 14 Datatypes 15 Built-in Types 15 Booleans 15 Numbers 15 Strings 16 Sequences and collections 16 Built-in constants 17 Testing the type of variables 18 Converting between datatypes 18 Explicit string type at definition of literals 19 Mutable and Immutable Data Types 19 Built in Modules and Functions 20 Block Indentation 24 Spaces vs. Tabs 25 Collection Types 25 Help Utility 30 Creating a module 31 String function - str() and repr() 32 repr() 33 str() 33 Installing external modules using pip 34 Finding / installing a package 34 Upgrading installed packages 34 Upgrading pip 35 Installation of Python 2.7.x and 3.x 35 Chapter 2: *args and **kwargs 38 Remarks 38 h11 38 h12 38 h13 38 Examples 39 Using *args when writing functions 39 Using **kwargs when writing functions 39 Using *args when calling functions 40 Using **kwargs when calling functions 41 Using *args when calling functions 41 Keyword-only and Keyword-required arguments 42 Populating kwarg values with a dictionary 42 **kwargs and default values 42 Chapter 3: 2to3 tool 43 Syntax 43 Parameters 43 Remarks 44 Examples 44 Basic Usage 44 Unix 44 Windows 44 Unix 45 Windows 45 Chapter 4: Abstract Base Classes (abc) 46 Examples 46 Setting the ABCMeta metaclass 46 Why/How to use ABCMeta and @abstractmethod 47 Chapter 5: Abstract syntax tree 49 Examples 49 Analyze functions in a python script 49 Chapter 6: Accessing Python source code and bytecode 51 Examples 51 Display the bytecode of a function 51 Exploring the code object of a function 51 Display the source code of an object 51 Objects that are not built-in 51 Objects defined interactively 52 Built-in objects 52 Chapter 7: Alternatives to switch statement from other languages 54 Remarks 54 Examples 54 Use what the language offers: the if/else construct. 54 Use a dict of functions 54 Use class introspection 55 Using a context manager 56 Chapter 8: ArcPy 58 Remarks 58 Examples 58 Printing one field's value for all rows of feature class in file geodatabase using Search 58 createDissolvedGDB to create a file gdb on the workspace 58 Chapter 9: Arrays 59 Introduction 59 Parameters 59 Examples 59 Basic Introduction to Arrays 59 Access individual elements through indexes 60 Append any value to the array using append() method 61 Insert value in an array using insert() method 61 Extend python array using extend() method 61 Add items from list into array using fromlist() method 61 Remove any array element using remove() method 61 Remove last array element using pop() method 62 Fetch any element through its index using index() method 62 Reverse a python array using reverse() method 62 Get array buffer information through buffer_info() method 62 Check for number of occurrences of an element using count() method 62 Convert array to string using tostring() method 63 Convert array to a python list with same elements using tolist() method 63 Append a string to char array using fromstring() method 63 Chapter 10: Asyncio Module 64 Examples 64 Coroutine and Delegation Syntax 64 Asynchronous Executors 65 Using UVLoop 66 Synchronization Primitive: Event 66 Concept 66 Example 66 A Simple Websocket 67 Common Misconception about asyncio 68 Chapter 11: Attribute Access 69 Syntax 69 Examples 69 Basic Attribute Access using the Dot Notation 69 Setters, Getters & Properties 69 Chapter 12: Audio 72 Examples 72 Audio With Pyglet 72 Working with WAV files 72 winsound 72 wave 72 Convert any soundfile with python and ffmpeg 73 Playing Windows' beeps 73 Chapter 13: Basic Curses with Python 74 Remarks 74 Examples 74 Basic Invocation Example 74 The wrapper() helper function. 74 Chapter 14: Basic Input and Output 76 Examples 76 Using input() and raw_input() 76 Using the print function 76 Function to prompt user for a number 76 Printing a string without a newline at the end 77 Read from stdin 78 Input from a File 78 Chapter 15: Binary Data 81 Syntax 81 Examples 81 Format a list of values into a byte object 81 Unpack a byte object according to a format string 81 Packing a structure 81 Chapter 16: Bitwise Operators 83 Introduction 83 Syntax 83 Examples 83 Bitwise AND 83 Bitwise OR 83 Bitwise XOR (Exclusive OR) 84 Bitwise Left Shift 84 Bitwise Right Shift 85 Bitwise NOT 85 Inplace Operations 87 Chapter 17: Boolean Operators 88 Examples 88 and 88 or 88 not 89 Short-circuit evaluation 89 `and` and `or` are not guaranteed to return a boolean 90 A simple example 90 Chapter 18: Call Python from C# 91 Introduction 91 Remarks 91 Examples 92 Python script to be called by C# application 92 C# code calling Python script 93 Chapter 19: Checking Path Existence and Permissions 95 Parameters 95 Examples 95 Perform checks using os.access 95 Chapter 20: ChemPy - python package 97 Introduction 97 Examples 97 Parsing formulae 97 Balancing stoichiometry of a chemical reaction 97 Balancing reactions 97 Chemical equilibria 98 Ionic strength 98 Chemical kinetics (system of ordinary differential equations) 98 Chapter 21: Classes 100 Introduction 100 Examples 100 Basic inheritance 100 Built-in functions that work with inheritance 101 Class and instance variables 101 Bound, unbound, and static methods 102 New-style vs. old-style classes 105 Default values for instance variables 106 Multiple Inheritance 107 Descriptors and Dotted Lookups 109 Class methods: alternate initializers 109 Class composition 111 Monkey Patching 112 Listing All Class Members 113 Introduction to classes 113 Properties 115 Singleton class 117 Chapter 22: CLI subcommands with precise help output 119 Introduction 119 Remarks 119 Examples 119 Native way (no libraries) 119 argparse (default help formatter) 120 argparse (custom help formatter) 120 Chapter 23: Code blocks, execution frames, and namespaces 123 Introduction 123 Examples 123 Code block namespaces 123 Chapter 24: Collections module 124 Introduction 124 Remarks 124 Examples 124 collections.Counter 124 collections.defaultdict 126 collections.OrderedDict 127 collections.namedtuple 128 collections.deque 129 collections.ChainMap 130 Chapter 25: Comments and Documentation 132 Syntax 132 Remarks 132 Examples 132 Single line, inline and multiline comments 132 Programmatically accessing docstrings 132 An example function 133 Another example function 133 Advantages of docstrings over regular comments 133 Write documentation using docstrings 134 Syntax conventions 134 PEP 257 134 Sphinx 135 Google Python Style Guide 136 Chapter 26: Common Pitfalls 137 Introduction 137 Examples 137 Changing the sequence you are iterating over 137 Mutable default argument 140 List multiplication and common references 141 Integer and String identity 145 Accessing int literals' attributes 146 Chaining of or operator 147 sys.argv[0] is the name of the file being executed 148 h14 148 Dictionaries are unordered 148 Global Interpreter Lock (GIL) and blocking threads 149 Variable leaking in list comprehensions and for loops 150 Multiple return 150 Pythonic JSON keys 151 Chapter 27: Commonwealth Exceptions 152 Introduction 152 Examples 152 IndentationErrors (or indentation SyntaxErrors) 152 IndentationError/SyntaxError: unexpected indent 152 Example 152 IndentationError/SyntaxError: unindent does not match any outer indentation level 153 Example 153 IndentationError: expected an indented block 153 Example 153 IndentationError: inconsistent use of tabs and spaces in indentation 153 Example 154 How to avoid this error 154 TypeErrors 154 TypeError: [definition/method] takes ? positional arguments but ? was given 154 Example 154 TypeError: unsupported operand type(s) for [operand]: '???' and '???' 155 Example 155 TypeError: '???' object is not iterable/subscriptable: 155 Example 155 TypeError: '???' object is not callable 156 Example 156 NameError: name '???' is not defined 156 It's simply not defined nowhere in the code 156 Maybe it's defined later: 156 Or it wasn't imported: 156 Python scopes and the LEGB Rule: 157 Other Errors 157 AssertError 157 KeyboardInterrupt 158 ZeroDivisionError 158 Syntax Error on good code 158 Chapter 28: Comparisons 160 Syntax 160 Parameters 160 Examples 160 Greater than or less than 160 Not equal to 161 Equal To 161 Chain Comparisons 162 Style 162 Side effects 162 Comparison by `is` vs `==` 163 Comparing Objects 164 Common Gotcha: Python does not enforce typing 165 Chapter 29: Complex math 166 Syntax 166 Examples 166 Advanced complex arithmetic 166 Basic complex arithmetic 167 Chapter 30: Conditionals 168 Introduction 168 Syntax 168 Examples 168 if, elif, and else 168 Conditional Expression (or "The Ternary Operator") 168 If statement 169 Else statement 169 Boolean Logic Expressions 170 And operator 170 Or operator 170 Lazy evaluation 170 Testing for multiple conditions 171 Truth Values 172 Using the cmp function to get the comparison result of two objects 172 Conditional Expression Evaluation Using List Comprehensions 173 Testing if an object is None and assigning it 174 Chapter 31: configparser 175 Introduction 175 Syntax 175 Remarks 175 Examples 175 Basic usage 175 Creating configuration file programatically 176 Chapter 32: Connecting Python to SQL Server 177 Examples 177 Connect to Server, Create Table, Query