首页 > 代码库 > python之random模块
python之random模块
random模块
用于生成随机浮点数、整数、字符串和随机抽取元素
方法:
random() 生成一个随机浮点数,范围在0.0~1.0之间
uniform(上限,下限) 在设置的范围内,随机生成一个浮点数(上下限可以是整数,浮点数)
randint(上限,下限) 在设定的范围内,随机生成一个整数(上下限必须为整数)
choice(序列) 从任何序列中选取一个随机的元素返回
shuffle(序列) 随机打乱一个序列中元素的顺序
sample(序列,长度) 从指定的序列中随机截取指定长度的片断,序列本身不做修改
例:
>>> import random
>>> random.random()
0.8447582194835284
random.uniform(1,5)
3.331346403458685
random.randint(1,5)
4
>>> a=range(1,10)
>>> random.choice(a)
64
>>> random.shuffle(a)
>>> print a
[7, 2, 5, 9, 1, 3, 4, 8, 6]
>>> random.sample(a,3)
[7, 5, 8]
猜数字游戏
会在1至99之间随机生成一个最终数字答案和一个幸运值,设定有6次机会,会根据输入大小进行比对 有相应提示。去试一试吧。如果猜中幸运值会增加机会哦。
import random
secret = random.randint (1,99)
guess = 0
tries = 0
print "AHOY! i‘m the Dread Pirate Roberts, and I have a secret!"
print "It is a number from 1 to 99. I‘ll give you 6 tries."
while guess != secret and tries < 6:
lucky = random.randint(1,99)
reward = random.choice(range(1,5))
# print lucky
guess = input( "What‘s yer guess?")
if guess < secret:
print "Too low,ye scurvy dog!"
elif guess > secret:
print "Too high,landlubber!"
tries += 1
if guess == lucky:
tries = tries - reward
print "You are lucky! Increase the chance of " + str(reward)
if guess == secret:
print "Avast! Ye got it! Found my secret,ye did!"
else:
print "No more guesses! Better luck next time,matey!"
print "The secret number was",secret
print "Lucky Numbers is " + str(lucky)
本文出自 “墨” 博客,请务必保留此出处http://jinyudong.blog.51cto.com/10990408/1916647
python之random模块