Dive into Python
Link
https://diveintopython.org/
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
import
statement. - 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
- Native datatypes: dictionaries, tuples and lists.
- Dictionaries define a one-on-one relationship between keys and values
- 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
orli *= 3
- 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.
- 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
- 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.
- Line continuation
- To continue a line, use
\
at the end of the line (_
in Visual Basic, not used in [C](…/C (programming language)/), Java, [[C Sharp|C#]])
- The
range
functionrange
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.
- 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.462500print "Today's stock price: %.2f" % 50.4625
50.46print "Change since yesterday: %+.2f" % 1.5
+1.50