0

This is the code, it should take an average of ether x or y coordinates when called how ever when y is called it gives an error.

import turtle
turtle.setup()
A = turtle.Turtle()

####################################################
total_of_x_scores = 0
total_of_y_scores = 0
number_of_x_scores = 0
number_of_y_scores = 0
average = 0

def average(axis):
    global total_of_x_scores
    global total_of_y_scores
    global number_of_x_scores
    global number_of_y_scores
    global average
    if axis=='x'or'X':
        x=A.xcor()
        total_of_x_scores += x #adding curent score
        number_of_x_scores += 1
        average=total_of_x_scores/number_of_x_scores
    else:
        y=A.ycor()
        total_of_y_scores += y #adding curent score
        number_of_y_scores += 1
        average=total_of_y_scores/number_of_y_scores
    return average
######################################################

while True:
    A.goto(100,100)
    print('x',average('x'))
    print('y',average('y'))

and this is the error, notice that it doesn't error on the x

x 100.0
Traceback (most recent call last):
 File "C:/Users/Jack/Desktop/average def.py", line 34, in <module>
    print('y',average('y'))
TypeError: 'float' object is not callable
jack
  • 90
  • 1
  • 8

1 Answers1

0

Even though you start out defining average as a number, you subsequently define average as a function. So the first time you call average(), it rightly understands it as a function. But since average is global, when the function completes, average is back to being a number again.

Here's a demonstration of the issue:

foo = 0

def foo():
    global foo
    foo = 1.0
    return foo

print('now foo is:', foo, 'and foo class is:', type(foo))
print('call foo() to get foo =', foo())
print('now foo is:', foo, 'and foo class is:', type(foo))
print('call foo() to get foo =', foo())

Output:

now foo is: <function foo at 0x1a27e108c8> and foo class is: <class 'function'>
call foo() to get foo = 1.0
now foo is: 1.0 and foo class is: <class 'float'>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1138-008d99aeffef> in <module>()
      2 print('call foo() to get foo =', foo())
      3 print('now foo is:', foo, 'and foo class is:', type(foo))
----> 4 print('call foo() to get foo =', foo())

TypeError: 'float' object is not callable
andrew_reece
  • 20,390
  • 3
  • 33
  • 58