Source
Adapted from my own handwritten and hand-typed notes from Year 1 to Year 3 of my EEE degree
Built-in Classes
Python has a small set of built-in classes that every program uses:
intfor integersfloatfor floating-point valuesboolfor the logical valuesTrueandFalselistfor an ordered sequence of objectsstrfor character stringssetfor an unordered collection of distinct objectsdictfor a dictionary (mapping from keys to values)
Calling the class name with no argument gives a default value, and calling it with an argument converts that value.
| Call | Result | Note |
|---|---|---|
int() | 0 | default |
int(3.14), int(-3.9) | 3, -3 | truncated towards zero |
int('137') | 137 | string to integer |
float() | 0.0 | default |
float(2), float('3.14') | 2.0, 3.14 | 6.022e23 means |
bool() | False | bool(x) is False for 0 or [], else True |
list() | [] | empty list |
list('hello') | ['h','e','l','l','o'] | one element per character |
set() | empty set | {} is an empty dict, not a set |
List, String, Set and Dict
Key facts:
- a list of length is indexed from to , holds any objects (even
None) and grows or shrinks as needed - a str uses single or double quotes, and triple quotes when the text spans several lines
- a set uses curly braces, e.g.
{'red', 'green', 'blue'}, and keeps no duplicates - a dict is a series of
key: valuepairs, e.g.{'sg': 'Singapore', 'de': 'Germany'}
Methods are called with the dot operator on an object, e.g. data.sort() sorts the list data in place.
Operators
The meaning of an operator depends on the operand types: a + b adds two numbers but concatenates two strings.
| Group | Operators | Meaning |
|---|---|---|
| Logical | not, and, or | negation, conditional and, conditional or |
| Equality | is, is not | same object identity, different identity |
| Equality | a == b, a != b | equivalent value, not equivalent |
| Comparison | <, <=, >, >= | natural order, numeric or lexicographic (case sensitive) |
| Arithmetic | +, -, * | int if both operands are int, else float |
| Arithmetic | /, //, % | true division (always float), integer division (truncated), modulo |
| Sequence | s + t, k * s | concatenation, repeat s times |
| Sequence | val in s, val not in s | containment check |
Sequences compare lexicographically: elements are compared one by one until the first difference. For example [5, 6, 9] < [5, 7] is True because at index 1.
print(7 / 2, 7 // 2, 7 % 2) # 3.5 3 1
print('ab' + 'cd', 3 * [0]) # abcd [0, 0, 0]
print(2 in [1, 2, 3]) # TrueThese classes and operators are the building blocks for control flow and functions.