python - 了解如何在我的 Python 类中定义函数并对我的代码输出感到困惑

标签 python python-2.7

问题:编写一个 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/

相关文章:

python - 有序关闭Python环境

python - 从 Anaconda 运行 Python 时出现 ImportError : No module named sysconfig,

python - 严重难以捉摸的循环(绞尽脑汁!)

python - 在python中打开文本文件作为数组或列表列表

python - 用 Python 阅读第 5 届 TIFF channel ?

python - 列表作为 python 中的引用类型

python - 有没有办法用 Python 绘制 3D 图元?

python - 同一图中的两个不同图形

python - 将 dict 列表转换为 int [Python Codecademy]

python - flask 导入错误