如何在Python中生成介于0和9(含)之间的随机整数?

例如,0、1、2、3、4、5、6、7、8、9


当前回答

对于Python 3.6,我有更好的运气

str_Key = ""                                                                                                
str_RandomKey = ""                                                                                          
for int_I in range(128):                                                                                    
      str_Key = random.choice('0123456789')
      str_RandomKey = str_RandomKey + str_Key 

只需添加“ABCD”和“ABCD”或“^!~=-><”等字符要更改要从中提取的字符池,请更改范围以更改生成的字符数。

其他回答

尝试random.randit:

import random
print(random.randint(0, 9))

文档状态:

随机随机(a,b)返回一个随机整数N,使得a<=N<=b。

尝试random.randrange:

from random import randrange
print(randrange(10))

random.sample是另一个可以使用的

import random
n = 1 # specify the no. of numbers
num = random.sample(range(10),  n)
num[0] # is the required number

试试看:

from random import randrange, uniform

# randrange gives you an integral value
irand = randrange(0, 10)

# uniform gives you a floating-point value
frand = uniform(0, 10)

您可以尝试从Python导入随机模块,然后让它在九个数字之间进行选择。这真的很基本。

import random
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    

如果以后要使用,可以尝试将计算机选择的值放在变量中,但如果不使用,打印功能应该这样工作:

choice = random.choice(numbers)
print(choice)