转眼间,小Mi带大家曾经机器学习了两个月了,明天带大家一起放松放松,咱们和电脑来几场简略的“决斗”!

场景1:
在没有丰盛表情包的聊天时代,大家的表情是不是纯正靠兔斯基和石头剪刀布来简略进行娱乐,要不明天安顿下和计算机无聊来几局?

逻辑剖析:

代码展现:
import random #导入随机模块

num = 1

lose_num = 0

win_num = 0

while num <= 3:

if lose_num == 2 or win_num == 2:    breakpeople = int(input('请出拳 0(石头) 1(剪刀) 2(布)'))if people > 2:    print('不能出大于2的值')else:    data = ['石头', '剪刀', '布']    computer = random.randint(0, 2)    print("您出的是{},电脑出的是{}".format(data[people], data[computer]))    if people == computer:        print('平局')        continue    elif (people == 0 and computer == 1) or (people == 1 and computer == 2) or (people == 2 and computer == 0):        print('你赢了')        win_num += 1    else:        print('你输了')        lose_num += 1

num += 1
运行后果:

场景2:
还记得大学期间外出聚餐的时候,偶然会呈现点多了饭菜的状况,这时候小Mi的室友秉持着“坚定不节约一丝一毫食粮”的良好习惯,突发奇想玩起了猜数字的游戏,随便选中0~99中的某个数字,猜中的人须要承受“惩办”,选中其中剩下的某一盘菜,当初想来,当前大伙在饭局中能够带上电脑进行这个游戏呀!顺带还能够在心仪的妹子背后小露一手!

逻辑剖析:

代码展现:
import random

import time

num = random.randint(1, 99)

print(num)

start = 0

end = 99

while 1 == 1:

peo = int(input('请输出{}到{}之间的数:'.format(start, end)))if peo > num:    print('大了')    end = peoelif peo < num:    print('小了')    start = peoelse:    print('BOOM!!!')    breakcom = random.randint(start + 1, end - 1)print('电脑输出:{}'.format(com))if com > num:    print('大了')    end = comelif com < num:    print('小了')    start = comelse:    print('BOOM!!!')    break

运行后果:

知识点:
敲重点!总结来说,这两个游戏代码中最重要的就是蕴含了一个random()函数,为了不便大家深刻理解,当初小Mi独自把这个函数的应用办法搬运给大家!

语法应用:
import random

random.random()

留神:random()是不能间接拜访的,须要导入 random 模块,而后通过 random 动态对象调用该办法,返回随机生成的一个实数,它在[0,1)范畴内。

实例:
1.简略应用
import random

生成第一个随机数

print "random() : ", random.random()

生成第二个随机数

print "random() : ", random.random()
以上实例运行后输入后果为:

random() : 0.281954791393

random() : 0.309090465205

2.random() 函数中常见的函数:
import random

print( random.randint(1,10) ) # 产生 1 到 10 的一个整数型随机数

print( random.random() ) # 产生 0 到 1 之间的随机浮点数

print( random.uniform(1.1,5.4) ) # 产生 1.1 到 5.4 之间的随机浮点数,区间能够不是整数

print( random.choice('tomorrow') ) # 从序列中随机选取一个元素

print( random.randrange(1,100,2) ) # 生成从1到100的距离为2的随机整数

a=[1,3,5,6,7] # 将序列a中的元素程序打乱

random.shuffle(a)

print(a)
3.Python 生成随机数、随机字符串
import random

import string

print random.sample('zyxwvutsrqponmlkjihgfedcba',5) # 多个字符中生成指定数量的随机字符

print''.join(random.sample(['z','y','x','w','v','u','t','s','r','q','p','o','n','m','l','k','j','i','h','g','f','e','d','c','b','a'], 5))

多个字符中选取指定数量的字符组成新字符串

print random.choice(['剪刀', '石头', '布'])

随机选取字符串

items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]print random.shuffle(items)

打乱排序

好啦,明天小Mi纯属无聊自娱自乐,带着大家傻傻乎乎编了两个小游戏,下周咱们持续开启新一轮机器算法的学习,咱们,下期见呦~(挥手十分钟!)