코딩 스쿨에 오신것을 환영합니다~~

질의응답 게시판

 
introduction to python p.323 s8-2 질문입니다.
나 * 신 | 2024-01-29

def find_word(data,number):
    new_data=data.sort(reverse=True)
    start=0
    end=len(data)-1
    while start<=end:
        mid=(end+start)//2
        if new_data[mid]==number:
            return mid
        elif new_data[mid]<number:
            end=mid-1
        else:
            start=mid+1
    return -1





lists=[55,3,-12,2,51,-23,17,9,13,16,30,9]
print(lists)
num=int(input("찾고자 하는 수를 입력하세요: "))
index=find_word(lists,num)
if index==-1:
    print("%d는 리스트에 존재하지 않는다"%num)
else:
    print("%d는 리스트에 존재한다17"%num)

위 코드의 if new_data[mid]==number:에서 계속
'NoneType' object is not subscriptable 라고 에러가 발생하는데 정확히
 어떤 에러인지 설명해주실 수 있나요?

  • 관 * 자
  • 2024-01-30 (12:07)
안녕하세요.

'NoneType' object is not subscriptable 

오류는 변수 new_data에 접근할수 없다는 것입니다.
이유는 sort() 메서드는 반환 값이 없습니다. None 값을 return합니다.

그런데 프로그램에서 new_data[mid]에서와 같이 인덱스로 접근하려고 하니
오류가 나오는 것입니다.

def find_word(data,number):
    new_data=data.sort(reverse=True)
    print(new_data)
    ...

위에서와 같이 print(new_data)로 찍어보시면 new_data, 즉 sort() 메서드의
반환 값이 None이라는 것을 알 수 있습니다.

도움이 되시길~~~