An operation is an action you can perform with a Python object. An object has a type and a value; its type determines which operations are available. A number can take part in arithmetic, while a string can be searched for a character. section 4.2 section 30.3
Add two values
In `a = 1`, the name `a` refers to an object with the value `1`. In `a = 1 + 2`, addition operates on two numbers; the expression `1 + 2` reduces to the value `3`. section 4.2
Different types offer different actions. Numbers support operations such as addition and division. Strings support indexing, slicing and replacing text. Lists can have an item appended. To call an operation that belongs to an object, use dot notation: `L.append()` tells Python to look for `append` on the list `L`. section 30.3
Table 5.1. Mathematical operations on ints and floats and the resulting types
| Operation(s) |
Type of second object |
Type of result |
Example |
||
|---|---|---|---|---|---|
| int | + - * ** % | int | int | 3 + 2 3 - 2 3 * 2 3 ** 2 3 % 2 | gives 5 gives 1 gives 6 gives 9 gives 1 |
| int | / | int | float | 3 / 2 | gives 1.5 |
| int | + - * / ** % | float | float | 3 + 2.0 3 - 2.0 3 * 2.0 3 / 2.0 3 ** 2.0 3 % 2.0 | gives 5.0 gives 1.0 gives 6.0 gives 1.5 gives 9.0 gives 1.0 |
| float | + - * / ** % | int | float | 3.0 + 2 3.0 - 2 3.0 * 2 3.0 / 2 3.0 ** 2 3.0 % 2 | gives 5.0 gives 1.0 gives 6.0 gives 1.5 gives 9.0 gives 1.0 |
| float | + - * / ** % | float | float | 3.0 + 2.0 3.0 - 2.0 3.0 * 2.0 3.0 / 2.0 3.0 ** 2.0 3.0 % 2.0 | gives 5.0 gives 1.0 gives 6.0 gives 1.5 gives 9.0 gives 1.0 |
Compare arithmetic operations on integers and floats, including how the operand types affect the result type. section 5.3
Some operations change an existing object. For example, list operations can modify a list in place rather than make a copy. You can also create your own object type with a class, choosing both its properties and the operations its objects will allow. section 25.0 section 31.0
