【问题标题】:Python function returns None instead of valuePython函数返回None而不是值
【发布时间】:2015-07-03 04:57:49
【问题描述】:

这是我的 Python 代码:

def pyramid_volume(base_length, base_width, pyramid_height):
    base_area = base_length * base_width
    pyramid_volume = base_area * pyramid_height * 1/3
    return

print('Volume for 4.5, 2.1, 3.0 is:', pyramid_volume(4.5, 2.1, 3.0))

它打印Volume for 4.5, 2.1, 3.0 is: None

有人可以帮我吗?

【问题讨论】:

    标签: python area function


    【解决方案1】:

    在 python 中,您必须指定要返回的内容。像这样:

    def pyramid_volume(base_length, base_width,pyramid_height):
        base_area=base_length*base_width
        pyramid_volume= base_area*pyramid_height*1/3
        return pyramid_volume
    
    print('Volume for 4.5, 2.1, 3.0 is: ', pyramid_volume(4.5, 2.1, 3.0))
    

    【讨论】:

    • @DavisThuy 的代码看起来像是来自 Pascal 的练习(如果您这样指定返回值)。在 python 中,我会避​​免创建与函数同名的局部变量(看起来不必要地让我感到困惑)。写return base_area*pyramid_height*1/3
    【解决方案2】:

    Python 中的每个函数都会返回一些对象。如果没有明确指定对象,则返回 None(Python 等效于 null)。通过编写return [nothing_here],您没有指定返回的内容,因此它返回默认值(None)。

    作为一种解决方案,明确指定应返回的内容:

    def pyramid_volume(base_length, base_width, pyramid_height):
        base_area = base_length * base_width
        pyramid_volume = base_area * pyramid_height * 1/3
        return pyramid_volume
    
    print('Volume for 4.5, 2.1, 3.0 is:', pyramid_volume(4.5, 2.1, 3.0)) # should print value
    

    【讨论】:

      猜你喜欢
      • 2018-03-08
      • 2018-06-25
      • 2020-10-17
      • 1970-01-01
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多