CoPoPHP
CoPoPHP

Reputation: 75

Python User Input Average

I'm trying to work on a school assignment that asks the user to input 3 integers, then I need to pass these three integers as parameters to a function named avg that will return the average of these three integers as a float value.

Here's what I've come up with so far, but I get this error:

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

Advice?

    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()

Upvotes: 1

Views: 2643

Answers (3)

OneOfOne
OneOfOne

Reputation: 99224

  1. You called avg without passing variables to it.
  2. You printed average which is only defined inside the avg function.
  3. You called avg after your print.

Change print (average) to

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

Upvotes: 0

Matt Woelk
Matt Woelk

Reputation: 2038

You should print(avg(a,b,c)) because the average variable is only stored in the function and cannot be used outside of it.

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117856

average only exists as a local variable inside the function 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)

Upvotes: 1

Related Questions