栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python随机生成范围内的数_python随机生成随机数?

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python随机生成范围内的数_python随机生成随机数?

利用 random 里的 seed 在需要的时候(测试阶段)确保每次生成的随机数相同

利用 random 里的 randint 指定范围

from random import seed, randint
import sys

try:
    get_seed = int(input('Give the seed for random with an integer: '))
except ValueError:
    print('Error here. Input is not an integer, giving up.')
    sys.exit()   

# prompts the user a strictly positive number, nb_of_elements.
try:
    nb_of_elements = int(input('How many elements do you want to generate? '))
except ValueError:
    print('Error here. Input is not an integer.')
    sys.exit()
if nb_of_elements <= 0:
    print('Error here. Input should be strictly positive.')
    sys.exit()

seed(get_seed)

# Generates a list of nb_of_elements random integers between -50 and 50.
L = [randint(-50, 50) for _ in range(nb_of_elements)]
# Prints out the list.
print('nThe list is:' , L)

运行得到(输入seed = 5, 生成 4 个随机数)

Give the seed for random with an integer:  5
How many elements do you want to generate? 4

The list is: [29, -18, 44, -5]

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/783373.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号