2014-03-14 105 views
1

我試圖在學校作業上要求用戶輸入3個整數,然後我需要將這三個整數作爲參數傳遞給名爲平均值的函數,該函數將返回這些函數的平均值三個整數作爲浮點值。Python用戶輸入平均

下面是我想出這麼遠,但我得到這個錯誤:

line 13, in <module> 
    print (average) 
NameError: name 'average' is not defined 

建議嗎?

a = float(input("Enter the first number: ")) 
    b = float(input("Enter the second number: ")) 
    c = float(input("Enter the third number: ")) 

    def avg(a,b,c): 
     average = (a + b + c)/3.0 
     return average 


    print ("The average is: ") 
    print (average) 

    avg() 
+0

「打印」 是一種說法,不是一個函數。你不應該圍繞你想要打印的方式使用括號。 – jrennie

+1

@jrennie OP沒有指定這是Python 2.x還是3.x,但如果這是Python 3,打印確實是一個函數,並且需要括號 – CoryKramer

+0

@Cyber​​ Doh!對不起,我的無知3.x – jrennie

回答

1

average只存在作爲函數avg

def avg(a,b,c): 
    average = (a + b + c)/3.0 
    return average 

answer = avg(a,b,c) # this calls the function and assigns it to answer 

print ("The average is: ") 
print (answer) 
+0

我可以看到我沒有通過變量出錯的地方。謝謝! – CoPoPHP

0

內的局部變量您應該print(avg(a,b,c))因爲average變量只存儲在功能,不能在其外部使用。

0
  1. 您稱之爲avg而不傳遞變量給它。
  2. 您打印的平均值只在avg函數中定義。
  3. 您打印後稱之爲平均值。

變化print (average)

average = avg(a, b, c); 
print(average)