Python (TypeError: unsupported type of operands to add: 'undefined' and 'str')

I am new to python. Please tell me what mistake I made.

list = [1,2,3,4]
print "elements:"
for a in list:
    print(a)
num=int(input("pick 1 element"))
print num + " is " + list.index(num)

Conclusion:

elements:
1
2
3
4
pick 1 element
2
TypeError: unsupported operand type(s) for Add: 'undefined' and 'str'

If i do num=stritValueError: list.index(x): x not in list

+3
source share
1 answer

Try:

print str(num) + " is " + str(list.index(num))

Your problem is that you need to numbe a string in its derivation, but when indexing in the list need to intbe int. Even simpler, you can use the features of the Python function printto do the conversion for you:

print num, "is", list.index(num)

Also, do not name your lists list, which is a built-in function in Python.

+2
source

All Articles