我有一个变量叫做"number"范围是变量"one_answers";b"。这些范围变量本身就是范围。
from random import *
a = randint(1, 99)
b = randint(2, 100)
number = randint(a, b)
print(number)
当我尝试输入这段代码时,我偶尔会收到一个整数或得到这个错误:
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)
需要确保传递给randint的第一个参数小于或等于第二个参数。如何:
from random import randint
a = randint(1, 99)
b = randint(a, 100)
number = randint(a, b)
print(number)
…这相当于:
from random import randint
number = randint(1, 100)
print(number)
randint(a, b)有条件
a <= b
由于您生成的a和b是随机范围,因此有时a大于b。您需要调整您的a和b范围,使a始终小于或等于b。
a = randint(1, 50)
b = randint(50, 100)
由于randint
的范围需要由上下边界组成,因此当b
随机低于a
时,脚本偶尔会中断。为了防止这种情况,确保b
不能低于a
。一个例子:
from random import *
a = randint(1, 99)
b = randint(a, 100)
number = randint(a, b)
print(number)
使用它似乎可以完成您要求的工作。
import random
a = random.randint(1, 99)
b = random.randint(2, 100)
number = random.randint(a, b)
print(number)
我运行这个没有任何错误。