하루한줄 코딩일기
[Python] TypeError: 'int' object is not callable 본문
📃 'int' object is not callable 에러
자릿수의 합 문제를 해결하던 중 작은 오류가 발생했다. digit_sum() 함수를 호출해 그 결과값을 'sum' 이라는 변수에 저장하고자 하는 과정에서 문제가 발생 한 것.
def digit_sum(x):
return sum(list(map(int,str(x))))
N = int(input())
arr = list(map(int, input().split()))
max = -9999999
answer = 0
for i in arr:
sum = digit_sum(i) #오류 발생 지점
if sum>max:
max = sum
answer = i
print(answer)
Traceback (most recent call last):
File "C:\Users\14Z980-GA50K\Desktop\AA\AA\AA.py", line 15, in <module>
sum = digit_sum(i)
File "C:\Users\14Z980-GA50K\Desktop\AA\AA\AA.py", line 6, in digit_sum
return sum(list(map(int,str(x))))
TypeError: 'int' object is not callable
👊 변수명으로 인한 오류
무의식적으로 내장함수 sum과 같은 이름의 변수를 생성해서 발생한 오류였다. 변수명을 지을 때 주의할 점은 예약어를 사용해서는 안되고, 이 외에도 내장함수 이름와 동일한 변수명은 피하는 것이 좋다는 것이다. 내장함수와 동일한 이름의 변수를 사용하면 그 다음부터 해당 함수를 호출할 수 없게 되기 때문이다.
문제가 발생한 위 코드는 sum을 변수명으로 설정한 후 같은 이름의 sum() 함수를 호출했으니, 중복으로 인한 오류가 발생할 수 밖에 없다. 변수명을 dsum으로 변경하여 해결했다.
'Languages. > Python' 카테고리의 다른 글
[Python] 정규표현식 re.sub을 이용한 문자열 치환하기 (0) | 2022.02.16 |
---|---|
[Python] 순열(permutations)과 조합(combinations) 구현하기 (0) | 2022.02.14 |
[Python] TypeError: 'dict_values' object is not subscriptable (0) | 2022.02.02 |
[Python] input()과 sys.stdin.readline()의 차이 (0) | 2022.01.27 |
Comments