Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.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 二进制搜索程序-类型错误:Can';t转换为';int';对象隐式地访问str_Python_Python 3.x_Binary Search - Fatal编程技术网

Python 二进制搜索程序-类型错误:Can';t转换为';int';对象隐式地访问str

Python 二进制搜索程序-类型错误:Can';t转换为';int';对象隐式地访问str,python,python-3.x,binary-search,Python,Python 3.x,Binary Search,我用Java用python编写了一个简单的二进制程序,现在我是python新手(不仅是新手,我还花了20天的时间学习) 我得到了这个错误: Enter the number of Element: 5 Traceback (most recent call last): File "C:\Users\raj\Documents\EclipseProject\PythonProject1\myProgram.py", line 15, in <module> print(

我用Java用python编写了一个简单的二进制程序,现在我是python新手(不仅是新手,我还花了20天的时间学习)

我得到了这个错误:

Enter the number of Element: 
5
Traceback (most recent call last):
  File "C:\Users\raj\Documents\EclipseProject\PythonProject1\myProgram.py", line 15, in <module>
    print("Enter "+int(n)+" Elements")
TypeError: Can't convert 'int' object to str implicitly
输入元素的编号:
5.
回溯(最近一次呼叫最后一次):
文件“C:\Users\raj\Documents\EclipseProject\PythonProject1\myProgram.py”,第15行,在
打印(“输入”+int(n)+“元素”)
TypeError:无法将“int”对象隐式转换为str
这是我的节目:

array = []

print("Enter the number of Element: ")
n = input()
n = int(n)

array = [n]

print("Enter "+int(n)+" Elements")

for i in (0, n):
    array[i] += input()

print("Enter the element, you want to find:")
search = input()
search = int(search)

first = 0
first = int(first)

last = n-1
last = int(last)

middle = (first+last) / 2
middle = int(middle)

while(first <= last):
    if array(middle) < search:
        first = middle + 1
        first = int(first)

    elif array[middle] == search:
        print(int(search)+" Value found at location "+int((middle+1)))
        break

    else:
        last = middle - 1
        last = int(last)
        middle = (first+last)/2
        middle = int(middle)

if first>last:
    print(int(search)+" is NOT present in the list!")
array=[]
打印(“输入元素编号:”)
n=输入()
n=int(n)
数组=[n]
打印(“输入”+int(n)+“元素”)
对于(0,n)中的i:
数组[i]+=input()
打印(“输入要查找的元素:”)
搜索=输入()
search=int(搜索)
第一个=0
first=int(first)
最后=n-1
last=int(last)
中间=(第一个+最后一个)/2
中间=整数(中间)
而(第一个最后一个:
打印(int(搜索)+“不在列表中!”)
当我在我的all程序中试图转换成整数时,我仍然得到了相同的错误

非常感谢您的帮助!!!

看到错误了吗?请尝试以下操作:

    print("Enter "+str(n)+" Elements")

“Enter”+int(n)+“Elements”
-您正在尝试连接字符串和int。Python不会这样做,您需要显式地将int转换为str,如下所示:
“Enter”+str(n)+“Elements”
为什么需要将其转换为
str
?因为literal
是一个str对象。您不能将int对象添加到str对象中,在本例中,您需要两个变量的类型相同,即str或int。为什么需要将其转换为
str
?因为它是
int
,并且需要是
str
才能与其他字符串连接。这就是错误消息告诉您的。
    print("Enter "+str(n)+" Elements")