二进制搜索程序 - TypeError:无法隐式地将'int'对象转换为str

时间:2021-01-12 18:21:42

I've made a simple Binary program in python from Java, At this moment I'm new in Python(Not just new but i've spent 20 days to learn it).

我用Java在python中创建了一个简单的二进制程序,此时我是Python的新手(不仅仅是新的,但我花了20天的时间来学习它)。

I'm getting this error:

我收到这个错误:

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

Here is my program:

这是我的计划:

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!")

As i tried in my all program to convert into Integers, But still i'm getting the same error.

正如我在我的所有程序中尝试转换为整数,但我仍然得到相同的错误。

Help would be appreciated!!!

帮助将不胜感激!

1 个解决方案

#1


    print("Enter "+int(n)+" Elements")
TypeError: Can't convert 'int' object to str implicitly

Do you see the error? Try this:

你看到错误吗?试试这个:

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

#1


    print("Enter "+int(n)+" Elements")
TypeError: Can't convert 'int' object to str implicitly

Do you see the error? Try this:

你看到错误吗?试试这个:

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