1 | print ("Hello, World!") |
1 2 3 4 5 | def main(): print("Hello, World!") if __name__ == '__main__': main () |
1 2 3 4 5 6 7 8 | import sys print ("Number of arguments:", len(sys.argv), "arguments") print ("Argument List:", str(sys.argv)) $ python3 test.py arg1 arg2 arg3 Number of arguments: 4 arguments. Argument List: ['test.py', 'arg1', 'arg2', 'arg3'] |
1 2 3 4 5 6 | # This is a single line comments """ This is a multi-line comment with docstrings Useful to comment out sections of code """ |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | # Numbers x + y # sum of x and y x - y # difference of x and y x * y # product of x and y x / y # quotient of x and y x // y # (floored) quotient of x and y x % y # remainder of x / y -x # x negated +x # x unchanged abs(x) # absolute value or magnitude of x int(x). # x converted to integer long(x) # x converted to long integer float(x). # x converted to floating point complex(re,I'm) # a complex number with real part re, imaginary part im. im defaults to zero. c.conjugate() # conjugate of the complex number c. (Identity on real numbers) divmod(x, y) # the pair (x // y, x % y) pow(x, y) # x to the power y x ** y # x to the power y |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | # Strings x = 'This is a string' y = "This is a string" z = """ This is a multi line strong That is split over lines and preserves line breaks """ >>> 'Py' 'thon' # 2 Strings next to each other are concatenated 'Python' len(x) == 16 ("is" in x) == True ("Keith" in x) == False x[0] == 'T' x[0:3] == 'This' x[:3] == 'This' x[10:] == 'string' x.upper() == 'THIS IS A STRING' x.lower() == 'this is a string' y = " A string with white space. " y.strip() == 'A string with white space.' "Hello".replace("H", "J") == "Jello" a = "Hello" b = "World" c = a + ", " + b + "!" c == "Hello, World!" name = "Keith" surname = "Sterling" "My name is {} {}".format(name, surname) "My name is {1}, {0} {1}".format(name, surname) # Escape Characters \' # Single Quote \\ # Backslash \n # New Line \r # Carriage Return \t # Tab \b # Backspace \f # Form Feed \ooo # Octal value \xhh # Hex value |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | # String Methods capitalize(). # Converts the first character to upper case casefold(). # Converts string into lower case center(). # Returns a centered string count() # Returns the number of times a specified value occurs in a string encode(). # Returns an encoded version of the string endswith(). # Returns true if the string ends with the specified value expandtabs(). # Sets the tab size of the string find() # Searches the string for a specified value and returns the position of where it was found format(). # Formats specified values in a string format_map(). # Formats specified values in a string index() # Searches the string for a specified value and returns the position of where it was found isalnum(). # Returns True if all characters in the string are alphanumeric isalpha(). # Returns True if all characters in the string are in the alphabet isascii(). # Returns True if all characters in the string are ascii characters isdecimal(). # Returns True if all characters in the string are decimals isdigit(). # Returns True if all characters in the string are digits isidentifier(). # Returns True if the string is an identifier slower(). # Returns True if all characters in the string are lower case isnumeric(). # Returns True if all characters in the string are numeric isprintable(). # Returns True if all characters in the string are printable isspace(). # Returns True if all characters in the string are whitespaces istitle() # Returns True if the string follows the rules of a title isupper(). # Returns True if all characters in the string are upper case join() # Converts the elements of an iterable into a string ljust() # Returns a left justified version of the string lower() # Converts a string into lower case lstrip(). # Returns a left trim version of the string maketrans(). # Returns a translation table to be used in translations partition(). # Returns a tuple where the string is parted into three parts replace(). # Returns a string where a specified value is replaced with a specified value rfind() # Searches the string for a specified value and returns the last position of where it was found rindex() # Searches the string for a specified value and returns the last position of where it was found rjust() # Returns a right justified version of the string rpartition() # Returns a tuple where the string is parted into three parts rsplit() # Splits the string at the specified separator, and returns a list rstrip() # Returns a right trim version of the string split() # Splits the string at the specified separator, and returns a list splitlines() # Splits the string at line breaks and returns a list startswith() # Returns true if the string starts with the specified value strip() # Returns a trimmed version of the string swapcase() # Swaps cases, lower case becomes upper case and vice versa title() # Converts the first character of each word to upper case translate() # Returns a translated string upper() # Converts a string into upper case zfill() # Fills the string with a specified number of 0 values at the beginning |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | # Bool ( Boolean ) bool(True) # True bool("abc") # True bool(123) # True bool(["apple", "cherry", "banana"]). # True bool(False) # False bool(None) # False bool(0) # False bool("") # False bool(()) # False bool([]) # False bool({}) # False X == Y # Equals X > Y # Greater than X >= Y # Greater than or equal X < Y # Less than X <= Y # Less than or equal X != Y # Not equal too X == Y # Are the same values X is Y # Are the same objects |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | # Lists ( And Arrays ) # Ordered. The order you create, order will not change # Mutable # Duplicates thislist = ["apple", "banana", "orange", "apple", "cherry"] thisList[0] == 'apple' thisList[0] = 'melon' thisList[0] != 'apple' thisList[0] == 'melon' thisList[-1] == 'cherry' thisList[-2] == 'apple' thisList[1:3] == ["banana", "orange", "apple"] thisList[:3] == ["apple", "banana", "orange", "apple"] thisList[2:] == ["orange", "apple", "cherry"] thislist[-4:-1] == ["banana", "orange", "apple"] len(thisList) == 4 type(mylist) == <class 'list'> thisList2 = list(("apple", "banana", "orange")) len(thisList2) == 3 # Ranges myRange = range(10) myList = list(range(10)) range(start, stop, step) range(0, 100) # 0, 1, 2, 3, ..... 100 range(0, 100, 10). # 0, 10, 20, 30, ... 100 |
1 2 3 4 5 6 7 8 9 10 11 12 13 | # List Methods append() # Adds an element at the end of the list clear() # Removes all the elements from the list copy() # Returns a copy of the list count() # Returns the number of elements with the specified value extend() # Add the elements of a list (or any iterable), to the end of the current list index() # Returns the index of the first element with the specified value insert() # Adds an element at the specified position pop() # Removes the element at the specified position remove() # Removes the first item with the specified value reverse() # Reverses the order of the list sort() # Sorts the list |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | # Tuples # Ordered # Immutable # Duplicates myTuple = (1, 2, 3) myTuple = (1, "Two", True) myTuple = tuple(1, 2, 3) type(myTuple) == <class 'tuple'> len(myTuple) == 3 myTuple[0] = 1 myTuple[-1] = 3 x = ("apple", "banana", "cherry") y = list(x) y[1] = "kiwi" x = tuple(y) thistuple = ("apple", "banana", "cherry") y = list(thistuple) y.append("orange") thistuple = tuple(y) thistuple = ("apple", "banana", "cherry") y = ("orange",) thistuple += y fruits = ("apple", "banana", "cherry") (green, yellow, red) = fruits tuple1 = ("a", "b" , "c") tuple2 = (1, 2, 3) tuple3 = tuple1 + tuple2 fruits = ("apple", "banana", "cherry") mytuple = fruits * 2 |
1 2 3 4 5 | # Tuple Methods count() Returns the number of times a specified value occurs in a tuple index() Searches the tuple for a specified value and returns the position of where it was found append() Appends an element to the tuple |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | # Dict ( Dictionary ) # Ordered ( Python 3.7 onwards ) # Mutable # No duplicates myDict = { "name": "Keith", "occupation": "developer", "age": 54 } myDict = dict(name = "Keith", occupation = "developer", age = 54) len(myDict) == 3 type(myDict) == <class 'dict'> myDict["name"] == "Keith" myDict["age"] == 54 myDict.get("name") == "Keith" myDict.get("age") == 54 myDict.keys() == dict_keys(['name', 'occupation', 'age']) myDict.update({"occupation": "software engineer"}) myDict["employer"] = "Inchkeith Consulting" myDict == {'name': 'Keith', 'occupation': 'software engineer', 'age': 54, 'employer': 'Inchkeith Consulting'} myDict.pop("age") myDict == {'name': 'Keith', 'occupation': 'software engineer', 'employer': 'Inchkeith Consulting'} myNewDict = myDict.copy() myNewDict == {'name': 'Keith', 'occupation': 'software engineer', 'employer': 'Inchkeith Consulting'} |
1 2 3 4 5 6 7 8 9 10 11 12 13 | # Dictionary Methods clear() # Removes all the elements from the dictionary copy() # Returns a copy of the dictionary fromkeys() # Returns a dictionary with the specified keys and value get() # Returns the value of the specified key items() # Returns a list containing a tuple for each key value pair keys() # Returns a list containing the dictionary's keys pop() # Removes the element with the specified key popitem() # Removes the last inserted key-value pair setdefault() # Returns the value of the specified key. If the key does not exist: insert the key, with the specified value update() # Updates the dictionary with the specified key-value pairs values() # Returns a list of all the values in the dictionary |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | # Set # Unordered # Immutable - but you can remove items and add new items. # Unindexed thisset = {"apple", "banana", "cherry"} thisset = set(("apple", "banana", "cherry")) thisset = set({"apple", "banana", "cherry"}) thisset = set(["apple", "banana", "cherry"]) # Duplicates are ignored thisset = {"apple", "banana", "cherry", "apple"} thisset == {"apple", "banana", "cherry"} ("banana" in thisset) == True ("fig" in thisset) == False thisset.add("fig") ("fig" in thisset) == True thisset = {"apple", "banana", "cherry"} tropical = {"pineapple", "mango", "papaya"} thisset.update(tropical) thisset == {"apple", "banana", "cherry", "pineapple", "mango", "papaya"} thisset = {"apple", "banana", "cherry"} mylist = ["kiwi", "orange"] thisset.update(mylist) thisset == {"apple", "banana", "cherry", "kiwi", "orange"} thisset = {"apple", "banana", "cherry"} thisset.remove("banana") thisset = {"apple", "cherry"} thisset.remove("peach") # Rasies an error if not exist thisset.discaard("peach") # Does not raise an error thisset.pop() # Removes a random item !!!! set1 = {"a", "b" , "c"} set2 = {1, 2, 3} set3 = set1.union(set2). # Returns a new set set1 = {"a", "b" , "c"} set2 = {1, 2, 3} set1.update(set2) # Adds set2 into set1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | # Set Methods add() # Adds an element to the set clear() # Removes all the elements from the set copy() # Returns a copy of the set difference() # Returns a set containing the difference between two or more sets difference_update() # Removes the items in this set that are also included in another, specified set discard() # Remove the specified item intersection() # Returns a set, that is the intersection of two or more sets intersection_update() # Removes the items in this set that are not present in other, specified set(s) isdisjoint() # Returns whether two sets have a intersection or not issubset() # Returns whether another set contains this set or not issuperset() # Returns whether this set contains another set or not pop() # Removes an element from the set remove() # Removes the specified element union() # Return a set containing the union of sets update() # Update the set with another set, or any other iterable |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | # Byte, ByteArray, MemoryView # Bitwise Operators x | y # bitwise or of x and y x ^ y # bitwise exclusive or of x and y x & y # bitwise and of x and y x << n # x shifted left by n bits x >> n # x shifted right by n bits ~x # the bits of x inverted # Byte message = 'Python is fun' byte_message = bytes(message, 'utf-8') byte_message == b'Python is fun' size = 5 arr = bytes(size) arr == b'\x00\x00\x00\x00\x00' # ByteArray prime_numbers = [2, 3, 5, 7] # convert list to bytearray byte_array = bytearray(prime_numbers) byte_array == bytearray(b'\x02\x03\x05\x07') string = "Python is interesting." arr = bytearray(string, 'utf-8') arr == bytearray(b'Python is interesting.') size = 5 arr = bytearray(size) arr == bytearray(b'\x00\x00\x00\x00\x00') # MemoryView random_byte_array = bytearray('ABC', 'utf-8') mv = memoryview(random_byte_array) mv[0] == 65 bytes(mv[0:2]) == b'AB' list(mv[0:3])) == [65, 66, 67] mv[1] = 90 mv == bytearray(b'AZC') |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | if a > b: do_something() if a > b: do_something() else: do_something_else() if a > b: do_something() elif a == b: do_theother() else: do_something_else() do_something() if a > b else do_something_else() if a > b and c > d: do_something() if a > b or c > d: do_something() if not a > b: do_something() if a > b: do_something() if b > c: # Nested If do_something() if a > b: pass # Do nothing |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | # While Loop a = 1 b = 10 while a > b: do_something () a += 1 a = 1 b = 10 while a > b: do_something () # When while clause is true a += 1 else: do_something_else() # When while clause is no longer true a = 1 b = 10 while a > b: if a == 3: continue # Skip the rest of the loop this time do_something () a += 1 a = 1 b = 10 while a > b: if a == 3: break. # Break out of the loop entirely do_something () a += 1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | # For Loop name = "Keith" for c in name: print(c) languages = ['Swift', 'Python', 'Go', 'JavaScript'] for language in languages: print(language) thislist = ["apple", "banana", "cherry"] for i in range(len(thislist)): print(thislist[I]) thistuple = ("apple", "banana", "cherry") for x in thistuple: print(x) thisset = {"apple", "banana", "cherry"} for x in thisset: print(x) for x in thisdict: print(x) print(thisdict[x]) for x in thisdict.values(): print(x) for x in thisdict.keys(): print(x) for x, y in thisdict.items(): print(x, y) fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | # List comprehensions # Create an arrange of numbers arr = [x for x in range(10)] # Do something with the values in the arr as we build it squares = [x*x for x in range(11)] # Nested loops nums1 = range(3) nums2 = range(4) nums=[(x,y) for x in nums1 for y in nums2] nums == [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)] # With conditions odd_even_list = ["Even" if i%2==0 else "Odd" for i in range(5)] odd_even_list = ['Even', 'Odd', 'Even', 'Odd', 'Even'] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | # Functions def myFunction(): print("Hellow, World!") myFunction() # Call function and print Hello, World! def myFunction(name): print("Hello, " + name) myFunction("Keith") # Call function and print Hello, Keith def myFunction(name, salutation): print("Hello, " + name + ", " + salutation) myFunction("Keith", "How are you?") # Call function and print Hello, Keith, How are you? def myFunction(*args): # Multiple args print("You passed " + len(args) + " args") print("The first is " + args[0]) def myFunction(arg1, arg2, arg3): print(arg1, arg2, arg3) myFunction(arg1="Hello", arg2="World", arg3="keith") def myFunction(**args): print("You passed " + len(args) + " args") print(args["arg1"], args["arg2"], args["arg3"]) myFunction(arg1="Hello", arg2="World", arg3="keith") def myFunction(hello="World")" print("Hello, "+hello) myFunction() myFunction("Keith") def addTwo(num1, num2): return num1+num2 def doNothing(): pass myLambda = lambda a, b, c: a + b + c print(myLambda(5, 6, 2)) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | # Classes # Empty Class class Programmer: pass # Class with attributes class Programmer: def __init__(self, name, age) self.name = name self.age = age # Class with attributes and methods class Programmer: def __init__(self, name, age) self._name = name self._age = age def get_name(self): return self._name def get_age(self): return self._age # class with attributes and methods and class attributes and class methods class Programmer: total = 0 def __init__(self, name, age): self._name = name self._age = age Programmer.total = Programmer.total + 1 def get_name(self): return self._name def get_age(self): return self._age def how_many_programmers(): return Programmer.total p1 = Programmer("keith", 54) p2 = Programmer("fred", 45) print(Programmer.how_many_programmers()) # inheritance class Architect(Programmer): def __init__(self, name, age, aws=True): Programmer.__init__(self, name, age) self._aws = was class Architect(Programmer): def __init__(self, name, age, aws=True): super().__init__(name, age) self._aws = True # abstract class from abc import ABC class MyABC(ABC): pass # magic methods dir(int) ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | # Iterators mytuple = ("apple", "banana", "cherry") myit = iter(mytuple) print(next(myit)) print(next(myit)) print(next(myit)) for x in mytuple: print(x) class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 20: x = self.a self.a += 1 return x else: raise StopIteration myclass = MyNumbers() myiter = iter(myclass) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | # Exceptions try: do_something() except: handle_error() try: do_something() except NameError as ne: handle_name_error(ne) try: do_something() except NameError: handle_name_error() except: handle_other_errors() try: do_something() except: handle_error() else: do_something_else_if_no_error() try: do_something() except: handle_error() finally: do_something_even_if_an_error() x = "hello" if not type(x) is int: raise TypeError("Only integers are allowed") |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # Modules # In a file called helloworld.py def greeting(): print("Hello, World!") # In another source file import helloworld helloworld.greeting () # In another source file import helloworld as hw hw.greeting () |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | # Sorting values = [5, 2, 3, 1, 4] sorted(values) == [1, 2, 3, 4, 5]. # Returns a new list values = [5, 2, 3, 1, 4] values.sort() == [1, 2, 3, 4, 5]. # Sorts list in place values = ["D", "C", "B", "A", "E"] sorted(values, key=str.lower) == ["a", "b", "c","d", "e"] student_tuples = [ ('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10), ] sorted(student_tuples, key=lambda student: student[2]) # sort by age [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] from operator import itemgetter, attrgetter sorted(student_tuples, key=itemgetter(2)) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] sorted(student_objects, key=attrgetter('age')) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] sorted(student_tuples, key=itemgetter(2), reverse=True) [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] sorted(student_objects, key=attrgetter('age'), reverse=True) [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | # Built in Functions A abs() aiter() all() any() anext() ascii() B bin() bool() breakpoint() bytearray() bytes() C callable() chr() classmethod() compile() complex() D delattr() dict() dir() divmod() E enumerate() eval() exec() F filter() float() format() frozenset() G getattr() globals() H hasattr() hash() help() hex() I id() input() int() isinstance() issubclass() iter() L len() list() locals() M map() max() memoryview() min() N next() O object() oct() open() ord() P pow() print() property() R range() repr() reversed() round() S set() setattr() slice() sorted() staticmethod() str() sum() super() T tuple() type() V vars() Z zip() _ __import__() |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | # Python Standard Library # Text Processing Services string — Common string operations re — Regular expression operations difflib — Helpers for computing deltas textwrap — Text wrapping and filling unicodedata — Unicode Database stringprep — Internet String Preparation readline — GNU readline interface rlcompleter — Completion function for GNU deadline # Binary Data Services struct — Interpret bytes as packed binary data codecs — Codec registry and base classes #Data Types datetime — Basic date and time types zoneinfo — IANA time zone support calendar — General calendar-related functions collections — Container datatypes collections.abc — Abstract Base Classes for Containers heapq — Heap queue algorithm bisect — Array bisection algorithm array — Efficient arrays of numeric values weakref — Weak references types — Dynamic type creation and names for built-in types copy — Shallow and deep copy operations pprint — Data pretty printer reprlib — Alternate repr() implementation enum — Support for enumerations graphlib — Functionality to operate with graph-like structures # Numeric and Mathematical Modules numbers — Numeric abstract base classes math — Mathematical functions cmath — Mathematical functions for complex numbers decimal — Decimal fixed point and floating point arithmetic fractions — Rational numbers random — Generate pseudo-random numbers statistics — Mathematical statistics functions Functional Programming Modules itertools — Functions creating iterators for efficient looping functools — Higher-order functions and operations on callable objects operator — Standard operators as functions # File and Directory Access pathlib — Object-oriented filesystem paths os.path — Common pathname manipulations fileinput — Iterate over lines from multiple input streams stat — Interpreting stat() results filecmp — File and Directory Comparisons tempfile — Generate temporary files and directories glob — Unix style pathname pattern expansion fnmatch — Unix filename pattern matching linecache — Random access to text lines shutil — High-level file operations # Data Persistence pickle — Python object serialization copyreg — Register pickle support functions shelve — Python object persistence marshal — Internal Python object serialization dbm — Interfaces to Unix “databases” sqlite3 — DB-API 2.0 interface for SQLite databases # Data Compression and Archiving zlib — Compression compatible with gzip gzip — Support for gzip files bz2 — Support for bzip2 compression lzma — Compression using the LZMA algorithm zipfile — Work with ZIP archives tarfile — Read and write tar archive files # File Formats csv — CSV File Reading and Writing configparser — Configuration file parser tomllib — Parse TOML files netrc — netrc file processing plistlib — Generate and parse Apple .plist files # Cryptographic Services hashlib — Secure hashes and message digests hmac — Keyed-Hashing for Message Authentication secrets — Generate secure random numbers for managing secrets # Generic Operating System Services os — Miscellaneous operating system interfaces io — Core tools for working with streams time — Time access and conversions argparse — Parser for command-line options, arguments and sub-commands getopt — C-style parser for command line options logging — Logging facility for Python logging.config — Logging configuration logging.handlers — Logging handlers getpass — Portable password input curses — Terminal handling for character-cell displays curses.textpad — Text input widget for curses programs curses.ascii — Utilities for ASCII characters curses.panel — A panel stack extension for curses platform — Access to underlying platform’s identifying data errno — Standard errno system symbols ctypes — A foreign function library for Python # Concurrent Execution threading — Thread-based parallelism multiprocessing — Process-based parallelism multiprocessing.shared_memory — Shared memory for direct access across processes # The concurrent package concurrent.futures — Launching parallel tasks subprocess — Subprocess management sched — Event scheduler queue — A synchronized queue class contextvars — Context Variables _thread — Low-level threading API # Networking and Interprocess Communication asyncio — Asynchronous I/O socket — Low-level networking interface ssl — TLS/SSL wrapper for socket objects select — Waiting for I/O completion selectors — High-level I/O multiplexing signal — Set handlers for asynchronous events mmap — Memory-mapped file support # Internet Data Handling email — An email and MIME handling package json — JSON encoder and decoder mailbox — Manipulate mailboxes in various formats mimetypes — Map filenames to MIME types base64 — Base16, Base32, Base64, Base85 Data Encodings binascii — Convert between binary and ASCII quopri — Encode and decode MIME quoted-printable data # Structured Markup Processing Tools html — HyperText Markup Language support html.parser — Simple HTML and XHTML parser html.entities — Definitions of HTML general entities # XML Processing Modules xml.etree.ElementTree — The ElementTree XML API xml.dom — The Document Object Model API xml.dom.minidom — Minimal DOM implementation xml.dom.pulldom — Support for building partial DOM trees xml.sax — Support for SAX2 parsers xml.sax.handler — Base classes for SAX handlers xml.sax.saxutils — SAX Utilities xml.sax.xmlreader — Interface for XML parsers xml.parsers.expat — Fast XML parsing using Expat # Internet Protocols and Support webbrowser — Convenient web-browser controller wsgiref — WSGI Utilities and Reference Implementation urllib — URL handling modules urllib.request — Extensible library for opening URLs urllib.response — Response classes used by urllib urllib.parse — Parse URLs into components urllib.error — Exception classes raised by urllib.request urllib.robotparser — Parser for robots.txt http — HTTP modules http.client — HTTP protocol client ftplib — FTP protocol client poplib — POP3 protocol client imaplib — IMAP4 protocol client smtplib — SMTP protocol client uuid — UUID objects according to RFC 4122 socketserver — A framework for network servers http.server — HTTP servers http.cookies — HTTP state management http.cookiejar — Cookie handling for HTTP clients xmlrpc — XMLRPC server and client modules xmlrpc.client — XML-RPC client access xmlrpc.server — Basic XML-RPC servers ipaddress — IPv4/IPv6 manipulation library # Multimedia Services wave — Read and write WAV files colorsys — Conversions between color systems Internationalization gettext — Multilingual internationalization services locale — Internationalization services # Program Frameworks turtle — Turtle graphics cmd — Support for line-oriented command interpreters shlex — Simple lexical analysis Graphical User Interfaces with Tk tkinter — Python interface to Tcl/Tk tkinter.colorchooser — Color choosing dialog tkinter.font — Tkinter font wrapper # Tkinter Dialogs tkinter.messagebox — Tkinter message prompts tkinter.scrolledtext — Scrolled Text Widget tkinter.dnd — Drag and drop support tkinter.ttk — Tk themed widgets tkinter.tix — Extension widgets for Tk # Development Tools typing — Support for type hints pydoc — Documentation generator and online help system doctest — Test interactive Python examples unittest — Unit testing framework unittest.mock — mock object library unittest.mock — getting started 2to3 — Automated Python 2 to 3 code translation test — Regression tests package for Python test.support — Utilities for the Python test suite test.support.socket_helper — Utilities for socket tests test.support.script_helper — Utilities for the Python execution tests test.support.bytecode_helper — Support tools for testing correct bytecode generation test.support.threading_helper — Utilities for threading tests test.support.os_helper — Utilities for os tests test.support.import_helper — Utilities for import tests test.support.warnings_helper — Utilities for warnings tests # Debugging and Profiling bdb — Debugger framework faulthandler — Dump the Python traceback pdb — The Python Debugger The Python Profilers timeit — Measure execution time of small code snippets trace — Trace or track Python statement execution tracemalloc — Trace memory allocations Software Packaging and Distribution distutils — Building and installing Python modules ensurepip — Bootstrapping the pip installer venv — Creation of virtual environments zipapp — Manage executable Python zip archives # Python Runtime Services sys — System-specific parameters and functions sysconfig — Provide access to Python’s configuration information builtins — Built-in objects __main__ — Top-level code environment warnings — Warning control dataclasses — Data Classes contextlib — Utilities for with-statement contexts abc — Abstract Base Classes atexit — Exit handlers traceback — Print or retrieve a stack traceback __future__ — Future statement definitions gc — Garbage Collector interface inspect — Inspect live objects site — Site-specific configuration hook Custom Python Interpreters code — Interpreter base classes codeop — Compile Python code # Importing Modules zipimport — Import modules from Zip archives pkgutil — Package extension utility modulefinder — Find modules used by a script runpy — Locating and executing Python modules importlib — The implementation of import importlib.resources – Resources importlib.resources.abc – Abstract base classes for resources ast — Abstract Syntax Trees symtable — Access to the compiler’s symbol tables token — Constants used with Python parse trees keyword — Testing for Python keywords tokenize — Tokenizer for Python source tabnanny — Detection of ambiguous indentation pyclbr — Python module browser support py_compile — Compile Python source files compileall — Byte-compile Python libraries dis — Disassembler for Python bytecode pickletools — Tools for pickle developers # MS Windows Specific Services msvcrt — Useful routines from the MS VC++ runtime winreg — Windows registry access winsound — Sound-playing interface for Windows # Unix Specific Services posix — The most common POSIX system calls pwd — The password database grp — The group database termios — POSIX style tty control tty — Terminal control functions pty — Pseudo-terminal utilities fcntl — The fcntl and ioctl system calls resource — Resource usage information syslog — Unix syslog library routines |