2016-03-19 51 views
0

在這個網站上有類似的問題,但我發現答案只適用於字符串輸出。例如截然不同的事情。想象一下,如果我有這個python程序:定義一個名爲avg4的函數。返回四個數字的平均值

#!/usr/bin/env python 

def printAndReturnNothing(): 
    x = "hello" 
    print(x) 

def printAndReturn(): 
    x = "hello" 
    print(x) 
    return x 

def main():`enter code here` 
    ret = printAndReturn() 
    other = printAndReturnNothing() 

    print("ret is: %s" % ret) 
    print("other is: %s" % other) 

if __name__ == "__main__": 
    main() 

你認爲什麼是輸出?

hello 
hello 
ret is : hello 
other is: None 

但是,問題是要定義一個叫做avg4的函數。它要求用戶輸入四個數字並返回四個數字的平均值。第二個問題要求定義一個叫做avg的函數。它要求用戶輸入三個數字並打印平均值。

難道這些是不一樣的輸出嗎?

這是我avg4代碼:

def avg4(a,b,c,d): 
    a=int(input(ënter a number") 
    b 
    c 
    d 
    avg=a+b+c+d/4 
    return 

當我喊它,它會提示用戶輸入四個數字,但不返回任何東西。而第二個,avg將打印平均值。

回答

1

您需要在def的末尾使用return聲明返回某些內容。還有一些你需要做的其他改變。您的新代碼將是這樣的:

def avg4(): # You don't need parameters for this function; they're overwritten by your input 
    a=int(input("Enter a number")) # Added missing quote and bracket 
    b=int(input("Enter a second number")) # Filled in inputs for b, c and d 
    c=int(input("Enter a third number")) 
    d=int(input("Enter a fourth number")) 
    avg=(a+b+c+d)/4 # Changed to suit BODMAS 
    return avg # Returns the variable avg 

現在你可以做到這一點,因爲avg回報的東西:

result = avg() 
0

avg4函數有幾個問題。嘗試使用

def avg4():  
    a=int(raw_input("Enter a number").strip())  
    b=int(raw_input("Enter a second number").strip()) 
    c=int(raw_input("Enter a third number").strip()) 
    d=int(raw_input("Enter a fourth number").strip()) 
    avg=float(a+b+c+d)/4.0 # avg must be float, not int 
    return avg 

... 
print avg4() 
相關問題