Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python(TypeError:Add:';未定义';和';str';的操作数类型不受支持)_Python_String_Undefined_Typeerror - Fatal编程技术网

Python(TypeError:Add:';未定义';和';str';的操作数类型不受支持)

Python(TypeError:Add:';未定义';和';str';的操作数类型不受支持),python,string,undefined,typeerror,Python,String,Undefined,Typeerror,我是python新手。请告诉我我犯了什么错误 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) 输出: elements: 1 2 3 4 pick 1 element 2 TypeError: unsupported operand type(s) for Add: 'undef

我是python新手。请告诉我我犯了什么错误

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)
输出:

elements:
1
2
3
4
pick 1 element
2
TypeError: unsupported operand type(s) for Add: 'undefined' and 'str'
如果我做了
num=str
这是
ValueError:list.index(x):x不在列表中

试试:

print str(num) + " is " + str(list.index(num))
您的问题是在输出时需要将
num
作为字符串,但在索引到列表时需要将其作为
int
。更简单的是,您可以利用Python的
print
功能为您进行转换:

print num, "is", list.index(num)
另外,请不要将列表命名为
list
,这是Python中的内置函数

str(list.index(num))
也打印“%s是%s”%(num,list.index(num))