0

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'?

Vy Do
  • 46,709
  • 59
  • 215
  • 313
  • Does this answer your question? [Shadows built-in names "function" and "module" with PyCharm](https://stackoverflow.com/questions/45214672/shadows-built-in-names-function-and-module-with-pycharm) – Mike Scotty Feb 25 '23 at 08:30
  • I read your link, I still did not understand. – Vy Do Feb 25 '23 at 08:35
  • 3
    Python has a built-in function [`sum`](https://docs.python.org/3/library/functions.html#sum) so that you can e.g. sum a list `sum([1,2,3]) == 6`. By assigning to a variable called `sum`, you "shadow" that function and can no longer access it. – Nick Feb 25 '23 at 09:10
  • 2
    A so-called "Master Class" that destroys/shadows the built-in *sum()* function carries little credibility in my opinion – DarkKnight Feb 25 '23 at 09:28

1 Answers1

3

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

rzlvmp
  • 7,512
  • 5
  • 16
  • 45