Operators, Functions and Methods
Last updated on 2026-10-19 | Edit this page
Overview
Questions
- What can I do with values of different types?
- What happens when I combine values of different types?
- What are functions and methods?
Objectives
- Use arithmetic operators on numbers and strings.
- Read and interpret error messages.
- Convert values from one type to another.
- Call built-in functions and string methods.
We continue with the variables from the previous episode:
Operators
An object’s type determines what the program can do with it.
OUTPUT
10
OUTPUT
3700
The same operators also work on strings, but they do something different:
OUTPUT
'LovelaceLovelace'
OUTPUT
'LovelaceLovelaceLovelaceLovelaceLovelaceLovelaceLovelaceLovelaceLovelaceLovelace'
We get an error if we try to add a number to a string.
ERROR
TypeError: can only concatenate str (not "int") to str
OUTPUT
'Lovelace10'
Reading error messages
Error messages can look intimidating, but they are there to help you.
Read the last line first: it tells you the type of the error
(here a TypeError) and a short description of what went
wrong. Above it, Python shows you the line of code where the error
happened.
Dividing two numbers always results in a float:
OUTPUT
0.04627837837837838
OUTPUT
float
Type conversion
Data that we read from files or from the web often arrives as text, even if it looks like a number.
ERROR
TypeError: unsupported operand type(s) for /: 'str' and 'int'
OUTPUT
5.0
Similarly, str() converts a value to a string and
float() converts it to a floating point number.
Functions and methods
The len() function tells us the length of an item. In
the case of a string, for example, it tells us how many characters it
contains.
OUTPUT
8
Methods are special types of function that are always bound to an object, the thing on the left of the dot. For now, the difference between a function and a method is not that relevant.
OUTPUT
'LOVELACE'
OUTPUT
'Lovelace'
OUTPUT
2
OUTPUT
'Love is everywhere'
Getting help
Use the built-in function help() to see the
documentation of a function or method, e.g. help(len) or
help(name.replace). In Jupyter, you can also put the cursor
inside the parentheses and press Shift+Tab.
String methods
Given title = "introduction to python", use string
methods to
- print the title in capital letters,
- count how many times the letter
"o"occurs, - replace
"python"with"pandas".
- The type of a value determines what an operator does with it.
- Read error messages from the bottom up: the last line names the error.
- Use
int(),float()andstr()to convert between types. - Functions are called with
function(arguments), methods withobject.method(arguments). - String methods return a new value and do not change the original string.