Python从入门到精通(第六篇,基础篇)

今天学习的是random随机函数,老规矩还是用pip install安装random库。

描述

random() 方法返回随机生成的一个实数,它在[0,1)范围内。

语法

以下是 random() 方法的语法:

import random

random.random()

注意:random()是不能直接访问的,需要导入 random 模块,然后通过 random 静态对象调用该方法。

参数

返回值

返回随机生成的一个实数,它在[0,1)范围内。

实例

(这是一个用随机函数学的模拟掷骰子)

import random
from random import randint

needs_go_on = False
first = (random.randint(1, 6) + random.randint(1, 6))
print(f'玩家一骰出了{first}点')
if (first == 8 or first == 12):
    print('玩家一胜')
elif (first == 2 or first == 5 or first == 10):
    print('玩家二胜')
else:
    needs_go_on = True
while needs_go_on:
    current = (random.randint(1, 6) + random.randint(1, 6))
    print(f'玩家一骰出了{current}点temp2')
    if (current == 8):
        print('玩家二胜!temp2')
        break
    elif (current == first):
        print('玩家一胜!temp2')
        break
    else:
        pass

以下是代码运行结果

更多内容请关注作者,我会持续更新的哦!!!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值