What is shadow built-in name 'sum'?

Question:

I am learning at https://github.com/donhuvy/Data-Structures-and-Algorithms-The-Complete-Masterclass/blob/main/1.%20Big%20O%20Notation/2%20-%20bigo-whileloop.py#L11 .

My environment: Python 3.9, PyCharm 2022

import time

t1 = time.time()

num = 100
if num < 0:
    print("Enter a positive number")
else:
    sum = 0
    while num > 0:
        sum += num
        num -= 1
    print("The sum is", sum)

t2 = time.time()
print((t2 - t1))

enter image description here

What is shadow built-in name ‘sum’?

Answers:

sum is a name of built-in function in python. Avoid to use built-in names for variables naming.

Does this example answering your question?

a = sum([1, 2])
print('Sum is', a)

print('---------')

sum = 6
a = sum([1, 2])
Sum is 3
---------
Traceback (most recent call last):
  File "example.py", line 7, in <module>
    a = sum([1, 2])
TypeError: 'int' object is not callable

Also it may be a good idea to avoid master-classes with improperly named variables

Answered By: rzlvmp
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.