问题:编写一个 Python 函数 square,它接受一个数字并返回该数字的平方。
这个函数接受一个数字并返回一个数字。
给出的代码:
def square(x):
'''
x: int or float.
'''
我的代码:
def square(x):
'''
x: int or float.
'''
x = x * x
print x
输出:
Test: square(-5.0)
Your output:
25.0
None
Correct output:
25.0
Test: square(3.17)
Your output:
10.0489
None
Correct output:
10.0489
Test: square(-3.4)
Your output:
11.56
None
Correct output:
11.559999999999999
为什么我的代码打印出 (a)“无”,在某些情况下 (b) 错误答案?
最佳答案
如果您不从函数返回任何值,默认情况下它将返回 None
。
因此,如果您尝试打印函数的返回值,您将得到 None
。因此,根本不打印函数调用的结果。
您可以更改您的函数以返回计算的正方形而不是打印它:
def square(x):
'''
x: int or float.
'''
return x * x
关于python - 了解如何在我的 Python 类中定义函数并对我的代码输出感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14913719/