简体   繁体   中英

I'm getting this error in python related to randint() and randrange()

My code is supposed to create a random string, an array filled with random numbers and a string, and a random integer. Here's my code:

from random import randint, randrange
x = randint(1, randrange(1, 200))
f = [randint(1, randrange(1, 200)), randint(1, randrange(1, 200)), randint(1, randrange(1, 200)), str(randint(1, randrange(1, 200)))]
b = 5

Here's the error:

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    f = [randint(1, randrange(1, 10)), randint(1, randrange(1, 56)), randint(1, randrange(1, 7)), str(randint(150, randrange(1, 200)))]
  File "/usr/local/lib/python3.6/random.py", line 221, in randint
    return self.randrange(a, b+1)
  File "/usr/local/lib/python3.6/random.py", line 199, in randrange
    raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (150,39, -111)

str(randint(150, randrange(1, 200))) can specify an empty range.

ValueError: empty range for randrange() (150,39, -111) 150 > 39, which makes it an empty range, as your starting value is higher than your stopping value.

If you had a valid range in randrange() such as randint(150, randrange(150, 200))

You would get a correct response: 151

https://docs.python.org/3/library/random.html#functions-for-integers

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