1
howManyNames = (float(input("Enter how many student names do you want to enter? ")))
studentNames = []
ages = []
averageAge = 0
counter = 0

while (counter < int(howManyNames)):
    studentNames.append(input("Enter student names. "))
    ages.append(float(input("Enter that persons age. ")))
    counter += 1

averageAge = (float(ages)) / (float(howManyNames))
print (averageAge)

I keep getting that TypeError: float() argument must be a string or a number

I know off but I can't seem to find my mistake, I know you can't divide an array with and float.... thanks everyone!

Jon Clements
  • 138,671
  • 33
  • 247
  • 280

1 Answers1

0

Change:

averageAge = (float(ages)) / (float(howManyNames))

to:

averageAge = sum(ages) / float(howManyNames)

(Note: I just removed the redundant parenthesis for aesthetic reasons.)

Explanation:

If you open a repl and type

In [2]: help(float)

you will get float's documentation which says:

Help on class float in module __builtin__:

class float(object)
 |  float(x) -> floating point number
 |  
 |  Convert a string or number to a floating point number, if possible.
 |  
 |  Methods defined here:
...

In other words, you can do:

In [3]: float(3)
Out[3]: 3.0

In [4]: float("3")
Out[4]: 3.0

but you cannot do:

In [5]: float([])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-79b9f7854b4b> in <module>()
----> 1 float([])

TypeError: float() argument must be a string or a number

because [] is a list and not a string or a number which is what will be acceptable to float according to its documentation. It also wouldn't make sense for float to accept a list because its purpose is to convert a string or number to a floating point value.

In your question you define:

ages = []

setting ages to [] (of type list.)

Of course to find the average, you need to take the sum of the values and divide by how many values that are there. Of course, python happens to have a built in sum function which will sum a list for you:

In [6]: sum([])
Out[6]: 0

In [7]: sum([1,2,3]) # 1 + 2 + 3
Out[7]: 6

Which you need only divide by the number of values to convert the average.

DJG
  • 6,413
  • 4
  • 30
  • 51
  • thanks man! How did you know right away? I am an amateur in python so if you can please elaborate on your answer it'll help me out a lot but, your code did work! Im assuming the sum() function added up all inputs then divided by my howManTimes variable. Right? –  Nov 13 '13 at 16:23
  • Exactly, I added more to my answer. – DJG Nov 13 '13 at 16:36