Write a function to calculate the average of two numbers. (Python.) Get a name that is not defined

advertisements

Alright, so I am new with python at the moment and I am absolutely confusing myself with such a simple task. I have to write a function to calculate the average of two numbers, but the user must input the numbers so the average should print out.

I keep getting a a name error, name 'number2' is not defined.Below is my code.

number1 = raw_input("Enter number1")
number2 =raw_input("Enter number2")

def average(number1, number2):
  return (number1 + number2) / 2
avg=average = (number1,number2)
print avg

I'm doing something wrong and I know its obvious but I can't quite put my finger on it.


You have defined average as a function, and you must use it as a function. Something like this:

number1 = raw_input("Enter number1")
number2 =raw_input("Enter number2")

def average(number1, number2):
  return (int(number1) + int(number2)) / 2.0

avg=average(number1,number2)
print avg

There were two other things too. You must convert string to integer, and to get a good average you have to divide them by 2.0 instad of 2. Onother way to solve it is to convert the string to float directly.