数学函数Python代码检查

4

大家好,我正在上Python入门课程,目前很喜欢并且无法停止练习。我认为我已经完成了练习,但是我有一个问题,就是在哪里开始列出变量,例如sum、difference、product等等。我使用Sublime Text,它们都是白色的,除了sum之外,为什么会这样?即使当我运行代码时数字似乎是准确的,这会对事情造成影响吗?

''' Write a program that prompts the user for two integers and then prints 
'''sum, difference, product, average, distance, max and min.

import math
number1 = float(input("Please enter an integer: "))
number2 = float(input("Please enter another integer: "))
print()
print()
sum = number1 + number2
difference = number1 - number2
product = number1 * number2
average = (number1 + number2) / 2
distance = abs(number1 - number2)
maximum = max(number1, number2)
minimum = min(number1, number2)

print("Sum between the two:",sum)
print("Difference between the two:",difference)
print("Product between the two:",product)
print("Average between the two:",average)
print("The distance between the two:",distance)
print("The maximum between the two:",maximum)
print("The minimum between the two:",minimum)

感谢您的时间。

2
sum 是 Python 中的内置函数,如果需要使用它,则应更改此名称。 - PRMoureu
如果您决定使用内置的sum函数,而您自定义的变量覆盖了它,那么在某个地方您将会收到一个TypeError - cs95
啊,好的,那很有道理。那代码本身怎么样?距离、最大值和最小值看起来还可以吗? - Matticus
我正在使用Python 2.7,它运行良好,您可能需要重新检查。sum是Python中预定义的函数,建议避免使用相同名称的变量。此外,请删除顶部引号和那些行。 - sudo
@Matticus,'maximum/minimum' 可以,内置函数是 'max/min'。 - PRMoureu
1个回答

2

在您的文本编辑器中出现sum是因为它也是一个函数名(译注:指Python内置函数)。因此,如果您希望在代码中稍后使用此函数,它将引发异常。

关于您的代码,有几点需要注意:

如果您不使用math,则无需import math

'''标记了注释的开始和结束。要注释掉单行,请使用#。您开头的注释应该是:

'''this is a multiline comment
and here it continues'''

# this is a single line comment

谢谢!我很感激您的反馈。关于我的距离、最大值和最小值代码,这些都做得正确吗?我有点按照我在课堂上记住的去做,这就是我想出来的。 - Matticus
@Matticus 是的,即使sum也能正常工作,唯一发生的事情就是您不能在后面使用sum()函数,这就是为什么它被认为是不良实践的原因。 - Honza Zíka
谢谢你的帮助。我现在完全明白了。 - Matticus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接