Home > Net >  How do I set a variable with the value being a random range, with variables set to have a random ran
How do I set a variable with the value being a random range, with variables set to have a random ran

Time:12-01

I have this variable called "number" with the range being the variables "a" and "b". These range variables are ranges themselves.

from random import *

a = randint(1, 99)
b = randint(2, 100)

number = randint(a, b)
print(number)

When I try to enter this code, I occasionally receive an integer or get this error:

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    number = randint(a, b)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/random.py", line 248, in randint
    return self.randrange(a, b 1)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/random.py", line 226, in randrange
    raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (17, 6, -11)

CodePudding user response:

You need to ensure that the first parameter passed to randint is less than or equal to the second parameter. How about:

from random import randint

a = randint(1, 99)
b = randint(a, 100)
number = randint(a, b)
print(number)

...which is equivalent to:

from random import randint

number = randint(1, 100)
print(number)

CodePudding user response:

randint(a, b) has a condition.

a <= b

Since you are generating a and b as random range, sometimes a is greater than b. You need to adjust your a and b range so that a is always less than or equal to b.

a = randint(1, 50)
b = randint(50, 100)

CodePudding user response:

As your range for randint needs to consist of a lower and upper boundary, your script will occasionally break when b is randomly lower than a. To prevent this, make sure b cannot be lower than a. An example:

from random import *

a = randint(1, 99)
b = randint(a, 100)

number = randint(a, b)
print(number)

CodePudding user response:

Using this it seems to do the job you asked.

import random

a = random.randint(1, 99)
b = random.randint(2, 100)

number = random.randint(a, b)
print(number)

I don't have any error running this.

  • Related