liveBook · Manning

Operation

As explained in Get Programming: Learn to code with Python

An operation is an action that can be performed by or with a Python object.

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

Type of first object

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

How Get Programming: Learn to code with Python covers it

How deep it goes
Defines operations as type-specific actions, works through arithmetic and dot notation, and introduces defining operations for classes.
Examples
Uses addition, string replacement, list appending and a table of arithmetic result types.
What it assumes
Introduces objects, types and variable names before using them to explain operations; assumes no prior object-model terminology.
What you can do after
Build it from scratch by defining operations for a Python class, then create objects of that type and use them.
How it connects
Connects operations to object types, variables, expressions, dot notation, mutable lists and classes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.