5

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!

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
Nan N
  • 65
  • 1
  • 4
  • you are iterating over `number` which is why you are getting an error – sam Oct 12 '15 at 01:01
  • Possible duplicate of [int object is not iterable?](http://stackoverflow.com/questions/1938227/int-object-is-not-iterable) – Daniel Brose Oct 12 '15 at 01:02
  • I looked at that link, and it does not help. If someone could answer me in detail, that'd be great. – Nan N Oct 12 '15 at 01:03

3 Answers3

2

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
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • Thank you, I did this and it actually worked. Will give you the credit in a minute or so. – Nan N Oct 12 '15 at 01:07
1

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...
lemonhead
  • 5,328
  • 1
  • 13
  • 25
1

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.

pppery
  • 3,731
  • 22
  • 33
  • 46