简体   繁体   中英

Selecting randint from range

from random import randint
number_of_trials = 100
range_of_random_numbers = 1000
for each in number_of_trials:
    print randint(range(range_of_random_numbers))

I am a beginner to python. When I try running the above code I get the error:

TypeError: 'int' object is not iterable

I'm trying to get a random number from a range (defined in range_of_numbers) to print a certain amount of times (defined in number_of_trials). Please help, what am I doing wrong?

Use range to make an iterable (list if you're using Python 2.x) which will be used for iteration.

and you need to pass two integer to random.randint , not an interable (or list):

from random import randint

number_of_trials = 100
range_of_random_numbers = 1000
for each in range(number_of_trials):
    print randint(0, range_of_random_numbers)

I think what you want to use is choice.

from random import choice

Then change

print randint(range(range_of_random_numbers))

to

print choice(range(range_of_random_numbers))

The choice function will randomly pick an element from a non-empty sequence.

One issue and one suggestion in your code -

  1. You are doing - for each in number_of_trails: - this is wrong, you are trying to iterate over an integer, you should do - for each in range(number_of_trails): .

  2. The best to use here is random.choice() (Instead of randint() ). Especially if the range_of_random_numbers is not continuous.

Example -

from random import choice
number_of_trials = 100
range_of_random_numbers = 1000
for each in range(number_of_trials):
    print choice(range(range_of_random_numbers))

From documentation of random.choice() -

Return a random element from the non-empty sequence seq.

It should be like

from random import randint
number_of_trials = 100
range_of_random_numbers = 1000
for each in range(number_of_trials):
    print randint(range(range_of_random_numbers))

You got the error due to the fact int object are not iterable that is :

ie)

for a in 1:
    print a

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM