Unsupported operand types [python is easy]

If you will try to apply some operator on unsupported operands python will show you an exception: unsupported operand type(s).

Simplest example:

>>> 1 + '2'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Who is operand and why it is not supported?

Here we have 3 examples which will all cause Unsupported operand types exception. Each example is binary operator: +, / and -. Binary because it accepts 2 operands: before and after operator. Operand could be constant of variable, e.g.:

age = 21
print(age + ' years old') # will also drop "TypeError: unsupported operand type(s) for +: 'int' and 'str'"

Note there is unary operators in Python, e.g. not True which will return False

Python does not know how to perform arithmetic operation with type int (1) and type str ('5'). That is why he just crashes with exception.

How to fix python unsupported operand types ?

Depends on your case. Most likely you just want to format them to strings.

Then do:

age = 21
print(f'{age} years old')

NOTE f'' is so-called f-string which works only in python 3.5+. In older pythons you could do insted '{} years old'.format(age) but better always use new software.

Exception - multiplication works with str and int

It just repeats string N times:

>>> 'Go' * 5
'GoGoGoGoGo'
#python
menu 8
Bruce Hardy profile picture
Nov 01, 2020
by Bruce Hardy

Best related

Other by Bruce Hardy