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!
As you may well be aware,
sumis a built-in function in Python (used for adding up items in lists, etc.). While Python allows us to usesumas 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 liketotal_suminstead.For example, comment out the first line and try to run the code. It should result in a
NameError, but it raises aTypeErrorinstead. Why? ANameErroronly occurs when Python cannot find a name anywhere (not in our local variables, global variables, or built-in functions). Because# sum = 0was commented out, Python didn't findsumas a variable, but it did find the pre-existing built-in functionsum()that comes built into Python. Therefore, it didn't raise aNameError.--
Thank you for this wonderful course!