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 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 returnFalse
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')
NOTEf''
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'