Hope
Hope

Reputation: 1

Python "for loop and def" practice and got "TypeError: 'int' object is not iterable"

Here is my coding as follows.

import random

import math

def count_hit_in_cirle(iteration):

    randX=random.uniform(-1.0,1.0) # returns a X random float in INclusive [-1.0, 1.0]
    randY=random.uniform(-1.0,1.0) # returns a y random float in INclusive [-1.0, 1.0]
    one_if_in_circle=0
    for i in range(iteration):
         def one_if_in_circle(randX, randY):
             if math.sqrt(randX*randX+randY*randY) <= 1:
                 return 1
             else:
                 return 0
    return (sum(one_if_in_circle(randX, randY)))

count_hit_in_cirle(1000)

But I got error like this:

count_hit_in_cirle(1000)
Traceback (most recent call last):

  File "<ipython-input-4-4dcc579bc645>", line 1, in <module>
    count_hit_in_cirle(1000)

  File "<ipython-input-3-4fbc77f1c9ec>", line 11, in count_hit_in_cirle
    return (sum(one_if_in_circle(randX, randY)))

TypeError: 'int' object is not iterable

And then I tried:

return (sum(one_if_in_circle(randX, randY)))

Still I got error:

"TypeError: 'function' object is not iterable"

Is there anyone who can tell me how I could fix my coding? Thank you so much

Upvotes: 0

Views: 100

Answers (2)

Barmar
Barmar

Reputation: 781350

It looks like you're trying to create a generator. You need to put the loop inside the function, not around it, and use yield instead of return.

def count_hit_in_cirle(iteration):

    randX=random.uniform(-1.0,1.0) # returns a X random float in INclusive [-1.0, 1.0]
    randY=random.uniform(-1.0,1.0) # returns a y random float in INclusive [-1.0, 1.0]
    one_if_in_circle=0
    def one_if_in_circle(randX, randY):
        for i in range(iteration):
            if math.sqrt(randX*randX+randY*randY) <= 1:
                yield 1
            else:
                yield 0
    return (sum(one_if_in_circle(randX, randY)))

Your function is just returning one integer, not a sequence that sum() can iterate over.

Upvotes: 1

Gilseung Ahn
Gilseung Ahn

Reputation: 2624

one_if_in_circle is defined as int type variable in one_if_in_circle=0 and as function in def one_if_in_circle(randX, randY). Change one of them.

Upvotes: 0

Related Questions