Dive into Python
Chapter 2
Section titled “Chapter 2”- 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.
- A function can have attributes.
- The first part of a function should be it’s “doc string”, which is available as an attribute called
__doc__on the function. - Modules (files) can be imported using the
importstatement. - Functions on imported modules are called using
modulename.functionname(). - Tabbing matters in Python.
- Everything is an object in Python. Almost everything has attributes and methods.
- 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
Section titled “Chapter 3”- Native datatypes: dictionaries, tuples and lists.
- 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()
- Defining:
- 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:
Gets a new list containing elements 1 and up to 3, but not including 3, of the original list.li[1:3]
- Slicing a list with one parameter only:
li[:3]
- Copying a list:
Returns a “slice” from the start to the end of the original list; but this is a new object, not a reference.li[:]
- 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:
This is slower than “extend” because it creates a new (combined) list and assigns it to the original variable.li = li + ['example', 'new']
- “Addition” to a list:
This is slower than “extend” because it creates a new (combined) list and assigns it to the original variable.li += ['two']
- “Multiply” a list:
orli = [1, 2] * 3li *= 3
- Defining:
- Booleans: called
TrueandFalse(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.
- 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,incan 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:
This returns a new tuple, not a list.t[1:3]
- Find out if a value is in a tuple (returns boolean):
"c" in li
- Defining a tuple:
- 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:
We have now three variables containing one letter each.(x, y, z) = ('a', 'b', 'd')
- Line continuation
- To continue a line, use
\at the end of the line (_in Visual Basic, not used in C, Java, C#)
- To continue a line, use
- The
rangefunctionrangereturns 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.
- Strings
- Concatenation:
Returns “abc”. Fails if any variable is not a string already."a" + "b" + "c"
- Formatting:
Returns “a b c”"%s b %s" % ("a", "c")
- Formatting with other types than strings:
Returns “a 1”"%s %d" % ("a", 1)
- Formatting numbers:
50.462500print "Today's stock price: %f" % 50.462550.46print "Today's stock price: %.2f" % 50.4625+1.50print "Change since yesterday: %+.2f" % 1.5
- Concatenation: