2016-01-08 46 views
0

我已經在python中編寫了一個程序,它顯示了最多三個數字..雖然程序很容易輸出引發了一個問題..下面是我寫的代碼::Python程序的輸出沒有意義

#Program to find maximum of three numbers using function 
def max_of_three(a,b,c): 
    if(a>b and a>c): 
     print("a is greater") 
    elif(b>a and b>c): 
     print("b is greater") 
    else: 
     print("c is greater") 
print("Enter three numbers...") 
a=int(input()) 
b=int(input()) 
c=int(input()) 
print(max_of_three(a,b,c)) 

現在,當我運行這個程序,在運行時::提供輸入後得到這個輸出

Enter three numbers... 
58 
45 
12 
a is greater 
None 

的reesult是好的。但我不明白的是,爲什麼單詞「無」正在打印?我的意思是什麼意思?

+4

刪除最後一個print,即'max_of_three(a,b,c)'就足夠了,因爲你在該函數內部添加了'print' func。 –

+0

如果a> b> c: –

回答

1

print(max_of_three(a,b,c))正試圖打印max_of_three的結果 - 但沒有一個 - 因此None

看起來像你打算max_of_three返回一個字符串,而不是直接打印值。這是「更好的」,因爲它將計算中的「狀態」顯示分開。

替代方法是隻需調用max_of_three(不print)即max_of_three(a,b,c);這工作,但現在你的計算總是打印出結果(即使你不希望它打印)

+0

(即Python函數隱式返回「None」),Python也允許您在條件中丟失'和',即 。見https://books.google.com.au/books?id=M2D5nnYlmZoC&pg=PT182&lpg=PT182&dq=python+implicitly+returns+none&source=bl&ots=vXXFEr7PLR&sig=yHmltvvVJL-SQxeHcBYyX4PijA4&hl=en&sa=X&ved=0ahUKEwj5po3Mv5nKAhWjMKYKHcsDBCgQ6AEIUjAI#v=onepage&q=python %20implicitly%20returns%20none&f = false –

+0

謝謝你..這清除了我的懷疑..我其實並沒有考慮它......這個函數實際上是打印和我把函數放在打印語句中..我不應該已經完成了...謝謝你的回覆.. :) –

0

既然你沒回您的功能max_of_three(a,b,c)中的任何值都不會返回任何值,因此輸出爲None

通過您的評論#Program to find maximum of three numbers using function假設,你可以通過返回的最大價值就意味着:

def max_of_three(a,b,c): 
    if(a>b and a>c): 
     print("a is greater") 
     return a 
    elif(b>a and b>c): 
     print("b is greater") 
     return b 
    else: 
     print("c is greater") 
     return c 

現在,函數應返回的最大價值,這是58:

Enter three numbers... 
58 
45 
12 
a is greater 
58 
+0

非常感謝你澄清...這是一個很大的幫助.. :) –