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:

  • int for integers
  • float for floating-point values
  • bool for the logical values True and False
  • list for an ordered sequence of objects
  • str for character strings
  • set for an unordered collection of distinct objects
  • dict for 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.

CallResultNote
int()0default
int(3.14), int(-3.9)3, -3truncated towards zero
int('137')137string to integer
float()0.0default
float(2), float('3.14')2.0, 3.146.022e23 means
bool()Falsebool(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: value pairs, 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.

GroupOperatorsMeaning
Logicalnot, and, ornegation, conditional and, conditional or
Equalityis, is notsame object identity, different identity
Equalitya == b, a != bequivalent 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
Sequences + t, k * sconcatenation, repeat s times
Sequenceval in s, val not in scontainment 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])         # True

These classes and operators are the building blocks for control flow and functions.