Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python – array length variable keeps changing into a 'none type'

So I’ve been trying to make a program that uses binary search for school, however whenever I try to run it, it comes back with an error of ‘TypeError: list indices must be integers or slices, not NoneType’

This is the code:

arr = [1,2,3,4,5,6,7]
find = 3
if len(arr)%2 != 0:
    half = int(len(arr)+1)
else:
    half = int(len(arr))
half = half/2
half = int(half)

while True:
    half = int(half)
    sort = arr[half]
    print(sort)
    if find < sort:
        half = print(half/2)
    elif find > sort:
        half = half+(half/2)
    elif find == sort:
        print(f"found at position {half}")

I clearly state that it is an integer, but it just doesn’t work and I don’t know why

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your problem is the line half = print(half/2). print is a function that doesn’t return anything (therefore it returns None), and you are assigning None to half then. You probably mean half = half/2, and if you want to print it, do so on the next line.

Also, take a look at the difference between / and // in python. If you use // to divide by two, it will always return an integer and you won’t need to manually convert it to an int using half = int(half).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading