python中random模块

random模块

简介

  • 导入: import random

操作相关

  • 随机小数
# 0-1直接的小数
random.random()

# 1-5之间的小数,不包含1和5
random.uniform(1, 5)
  • 随机整数
# 1-10之间的整数,包含1和10  [1,10]
random.randint(1, 10)

# 1-10之间的整数,包含1,不包含10  [1, 10)
random.randrange(1, 10)

# 1, 4, 7中随机一个,不包含10
random.randrange(1, 10, 3)
  • 随机抽取
option = ['add', 'rm', 'mv']
random.choice(option)  # 从option中随机挑选一个
random.sample(option, 2)  # 从option中随机挑选不重复的两个,返回列表
  • 打乱顺序
nums = [1, 2, 3, 4, 5]
random.shuffle(nums)  # 打乱nums的顺序,无返回值,修改nums
# nums: [5, 4, 1, 3, 2]

示例

  • 生成一个指定位数的随机验证码
import random
from string import ascii_letters, digits
# ascii_letters: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
# digits: 0123456789


def gen_pin(n=4):
    """ 默认生成的是4位数验证码 """
    pin = ''
    c_list = [c for c in (ascii_letters + digits)]
    for i in range(n):
        pin += random.choice(c_list)
    
    return pin

if __name__ == '__main__':
    res = gen_pin(6)
    print(res)
  • 人机大战(石头剪刀布)
import random


def game(count=1):
    game_result = {'player': 0, 'computer': 0}
    option = ['石头', '剪刀', '布']
    # 玩家赢的选项
    player_win = [['石头', '剪刀'], ['剪刀', '布'], ['布', '石头']]

    while count:
        player_option = input('请输入你的选择(石头/剪刀/布): ')
        if player_option not in option:
            print('选项错误,请重新输入')
            continue

        com_option = random.choice(option)
        if [player_option, com_option] in player_win:
            print(f'你赢了,电脑出的是{com_option}')
            game_result['player'] += 1
        elif player_option == com_option:
            print(f'平局,电脑出的是{com_option}')
        else:
            print(f'你输了,电脑出的是{com_option}')
            game_result['computer'] += 1
        
        count -= 1
    
    print(f'你赢的次数{game_result["player"]},电脑赢的次数{game_result["computer"]}')

if __name__ == '__main__':
    game(3)
  • 5
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值