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?

Operand and Operator explanation

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

age = 21
print(age + ' years old') # will also drop "TypeError: unsupported operand type(s) for +: 'int' and 'str'"
Note: there are unary operators in Python, e.g. not True which will return False

Python does not know how to perform the arithmetic operation with the type int (1) and type str ('5'). That is why he just crashes with an 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 a so-called f-string that works only in python 3.5+. In older python versions you could do instead '{} years old'.format(age) but better always use new software with jucy sweet f-strings.

Exception - multiplication works with str and int

It just repeats string N times:

>>> 'Go' * 5
'GoGoGoGoGo'

#python
8
Bruce Hardy profile picture
Nov 01, 2020
by Bruce Hardy
Did it help you?
Yes !
No

Best related

Other by Bruce Hardy