Skip to content

Shadowing a Built-in Function (Part 1, 4: Arithmetic operations) #62

Description

@mpaunovic
sum = 0

number = int(input("First number: "))
sum = sum + number

number = int(input("Second number: "))
sum = sum + number

number = int(input("Third number: "))
sum = sum + number

print(f"The sum of the numbers: {sum}")

As you may well be aware, sum is a built-in function in Python (used for adding up items in lists, etc.). While Python allows us to use sum as a variable name, it "shadows" the built-in function, which can lead to confusing bugs later in our code. It is safer to use a name like total_sum instead.

For example, comment out the first line and try to run the code. It should result in a NameError, but it raises a TypeError instead. Why? A NameError only occurs when Python cannot find a name anywhere (not in our local variables, global variables, or built-in functions). Because # sum = 0 was commented out, Python didn't find sum as a variable, but it did find the pre-existing built-in function sum() that comes built into Python. Therefore, it didn't raise a NameError.

--

Thank you for this wonderful course!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions