Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep getting TypeError: 'int' object is not iterable

I keep getting this error: TypeError: 'int' object is not iterable.

My assignment that I need to (so you have some background on what I am trying to achieve) is this: "Write a program that will create 100 random integer numbers, both negative and positive between -10 and +10 (in a for loop) and then determine how many were positive and how many were negative. Finally, print out how many numbers were positive and how many numbers were negative."

import random

positive = 0
negative = 0

for number in random.randrange(-10,10):
    if number > 0:
        positive += 1
    else:
        negative += 1
print ("End")

That's my code so far. If anyone can help me using the above information and my error, that'd be great!

like image 630
Nan N Avatar asked Sep 27 '22 12:09

Nan N


3 Answers

random.randrange(-10,10) creates a single random integer, it does not automatically create 100 random integers. Hence when you try to do - for number in random.randrange(-10,10): - it errors out as you are trying to iterate over an integer which should not be possible.

I would suggest iterating over range(100) , and then taking random.randrange(-10,10) inside the loop. Example -

for _ in range(100):
    number = random.randrange(-10,10)
    if number > 0:
        positive += 1
    else:
        negative += 1
like image 183
Anand S Kumar Avatar answered Oct 18 '22 22:10

Anand S Kumar


random.randrange() is a function that returns a single random number. Your code is erroring out because you are then trying to loop over that single number like it is iterable.

Instead, you want to generate a random number 100 separate times, so your for loop should instead look something like this:

for i in range(100):
    number = random.randrange(-10,10)
    # do stuff with number...
like image 1
lemonhead Avatar answered Oct 18 '22 23:10

lemonhead


random.randrange(-10,10) returns a random number in range(-10,10), which is not iterable. random.randrange(-10,10) for _ in range(100) will do what you want. Also, you never print out the positive and negative counts.

like image 1
pppery Avatar answered Oct 18 '22 22:10

pppery