{ claus.conrad }

Dive into Python

https://diveintopython.org/

Chapter 2

  1. Python is dynamically typed and strongly typed:
    • Types are determined at runtime.
    • Types cannot be cast implicitly, nor can an existing variable get another type through assignment.
  2. A function can have attributes.
  3. The first part of a function should be it’s “doc string”, which is available as an attribute called __doc__ on the function.
  4. Modules (files) can be imported using the import statement.
  5. Functions on imported modules are called using modulename.functionname().
  6. Tabbing matters in Python.
  7. Everything is an object in Python. Almost everything has attributes and methods.
  8. If a module is run directly, it’s __name__ attribute equals __main__, otherwise (if it is imported) it’s __name__ attribute equals the filename with path or extension.

Chapter 3

  1. Native datatypes: dictionaries, tuples and lists.
  2. Dictionaries define a one-on-one relationship between keys and values
    • Defining:
      d = {"server": "mpilgrim", "database": "master"}
      
    • Getting value by key:
      d["server"]
      
    • Setting value by key:
      d["database"] = "pubs"
      
    • Adding key with value:
      d["uid"] = "sa"
      
    • Key names are case-sensitive.
    • Dictionary values can be any datatype, including strings, integers, objects, or even other dictionaries. And within a single dictionary, the values don’t all need to be the same type; you can mix and match as needed.
    • Dictionary keys are more restricted, but they can be strings, integers, and a few other types. You can also mix and match key datatypes within a dictionary.
    • Deleting a key:
      del d[42]
      
    • Deleting all keys:
      d.clear()
      
  3. Lists are like “ArrayList” (.NET) or “Vector” (Java), and they are ordered
    • Defining:
      li = ["a", "b", "mpilgrim", "z", "example"]
      
    • Getting by index:
      li[0]
      
    • They are zero-based.
    • Getting by reverse index:
      • li[−1] gets the last index,
      • li[-2] gets the second-last index etc.
    • Slicing a list:
      li[1:3]
      
      Gets a new list containing elements 1 and up to 3, but not including 3, of the original list.
    • Slicing a list with one parameter only:
      li[:3]
      
    If the left-hand parameter is missing it is assumed to be 0 and if the right-hand parameter is missing it is assumed to be -1 (the last element in the list, the one with the highest index).
    • Copying a list:
      li[:]
      
      Returns a “slice” from the start to the end of the original list; but this is a new object, not a reference.
    • Appending element to the end of a list:
      li.append("new")
      
    • Inserting at a specific place in the list:
      li.insert(2, "new")
      
    • Concatenating lists:
      li.extend(["two", "elements"])
      
    • Find index by value:
      li.index("example")
      
    • Find out if a value is in a list (returns boolean):
      "c" in li
      
    • Deleting list element by value (only the first element where the value matches - values can exist several times in a list):
      li.remove("z")
      
    • Remove and return the last element (use list as a queue):
      li.pop()
      
    • Append one list to another:
      list.extend(otherlist)
      
    • Concatenate two lists and return a new:
      li = li + ['example', 'new']
      
      This is slower than “extend” because it creates a new (combined) list and assigns it to the original variable.
    • “Addition” to a list:
      li += ['two']
      
      This is slower than “extend” because it creates a new (combined) list and assigns it to the original variable.
    • “Multiply” a list:
      li = [1, 2] * 3
      
      or
      li *= 3
      
  4. Booleans: called True and False (case-sensitive!)
    • 0 is False; all other numbers are True.
    • An empty string ("") is False, all other strings are True.
    • An empty list ([]) is False; all other lists are True.
    • An empty tuple (()) is False; all other tuples are True.
    • An empty dictionary ({}) is False; all other dictionaries are True.
  5. Tuples behave much like lists, but are “immutable” (constant). They cannot be extended or append to, nor can items be inserted into them, nor can items be removed or popped. It is not possible to call index() to get the index of an item in a tuple - they have no methods at all.
    However, in can be used to check if an item is contained in a tuple.
    • Defining a tuple:
      t = ("a", "b", "mpilgrim", "z", "example")
      
    • Getting by index:
      t[0]
      
    • Getting by reverse index:
      t[−1]
      
    • Slicing:
      t[1:3]
      
      This returns a new tuple, not a list.
    • Find out if a value is in a tuple (returns boolean):
      "c" in li
      
  6. Variables
    • Variables don’t need to be declared. They start existing the first time they are assigned a value, and stop existing when they get out of scope.
    • Variables don’t need to be declared with a type. They get their type the first time they are assigned a value, but the type cannot be changed later.
    • A variable cannot be referenced until it exists (has been assigned a value).
    • Assigning multiple variables at once using tuples:
      (x, y, z) = ('a', 'b', 'd')
      
      We have now three variables containing one letter each.
  7. Line continuation
    • To continue a line, use \ at the end of the line (_ in Visual Basic, not used in C, Java, [[r.dev.c-sharp|C#]])
  8. The range function
    • range returns a list of integers.
    • range(3) returns [0, 1, 2]
    • (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7) Declares 7 variables (MONDAY, TUESDAY, etc.) with the values 0, 1, etc. respectively.
  9. Strings
    • Concatenation:
      "a" + "b" + "c"
      
      Returns “abc”. Fails if any variable is not a string already.
    • Formatting:
      "%s b %s" % ("a", "c")
      
      Returns “a b c”
    • Formatting with other types than strings:
      "%s %d" % ("a", 1)
      
      Returns “a 1”
    • Formatting numbers:
      print "Today's stock price: %f" % 50.4625
      
      50.462500
      print "Today's stock price: %.2f" % 50.4625
      
      50.46
      print "Change since yesterday: %+.2f" % 1.5
      
      +1.50