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!
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
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With