2015-04-24 92 views
1

這是我的Python代碼:Python函數返回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 

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

有人能幫助我嗎?

回答

3

在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)) 
+3

通過@DavisThuy代碼看起來像帕斯卡爾來練習(被指定這樣的返回值)。在Python中,我會避​​免創建一個與函數同名的局部變量(看起來不必要地混淆了我)。只要寫'return base_area * pyramid_height * 1/3'即可 – kratenko

0

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 
相關問題