菜鸟教程 -- 学的不仅是技术,更是梦想!

Python 3 教程
Python3 教程 Python3 简介 Python3 环境搭建 Python3 VScode Python3 基础语法 Python3 基本数据类型 Python3 数据类型转换 Python3 解释器 Python3 注释 Python3 运算符 Python3 数字(Number) Python3 字符串 Python3 列表 Python3 元组 Python3 字典 Python3 集合 Python3 条件控制 Python3 循环语句 Python3 编程第一步 Python3 推导式 Python3 迭代器与生成器 Python3 with Python3 函数 Python3 lambda Python3 装饰器 Python3 数据结构 Python3 模块 Python __name__ Python3 输入和输出 Python3 File Python3 OS Python3 错误和异常 Python3 面向对象 Python3 命名空间/作用域 Python 虚拟环境的创建 Python 类型注解 Python3 标准库概览 Python3 实例 Python 测验

Python3 高级教程

Python3 正则表达式 Python3 CGI编程 Python3 MySQL(mysql-connector) Python3 MySQL(PyMySQL) Python3 网络编程 Python3 SMTP发送邮件 Python3 多线程 Python3 XML 解析 Python3 JSON Python3 日期和时间 Python3 内置函数 Python3 MongoDB Python3 urllib Python uWSGI 安装配置 Python3 pip Python3 operator Python math Python requests Python random Python OpenAI Python 有用的资源 Python AI 绘画 Python statistics Python hashlib Python 量化 Python pyecharts Python selenium 库 Python 爬虫 Python Scrapy 库 Python Markdown Python sys 模块 Python Pickle 模块 Python subprocess 模块 Python queue 模块 Python StringIO 模块 Python logging 模块 Python datetime 模块 Python re 模块 Python csv 模块 Python threading 模块 Python asyncio 模块 Python PyQt Python for 循环 Python while 循环
(追記) (追記ここまで)

Python 随机数生成

Document 对象参考手册 Python3 实例

在 Python 中,可以使用内置的 random 模块来生成随机数。

import random

random.random()

random.random() 返回一个介于 0.0 和 1.0 之间的随机小数:

实例

import random

random_number = random.random()
print(random_number)

执行以上代码输出结果为:

0.7597072251250637

random.randint(a, b)

random.randint(a, b) 用于返回一个介于 a 和 b 之间的整数(包括 a 和 b)。

random.randint(a,b)

函数返回数字 N ,N 为 a 到 b 之间的数字(a <= N <= b),包含 a 和 b。

以下实例演示了如何生成一个 0 ~ 9 之间随机数:

实例

# -*- coding: UTF-8 -*-# Filename : test.py# author by : www.runoob.com# 生成 0 ~ 9 之间的随机数# 导入 random(随机数) 模块importrandomprint(random.randint(0,9))

执行以上代码输出结果为:

4

random.choice(sequence)

random.choice(sequence) 用于从序列中随机选择一个元素:

实例

import random

list1 = [1, 2, 3, 4, 5]
random_element = random.choice(list1)
print(random_element)

实例

import random

list1 = [1, 2, 3, 4, 5]
random_element = random.choice(list1)
print(random_element)

执行以上代码输出结果为:

4

random.shuffle(sequence)

random.shuffle(sequence) 用于将序列中的元素进行随机排序:

实例

import random

list1 = [1, 2, 3, 4, 5]
random.shuffle(list1)
print(list1)

执行以上代码输出结果为:

[3, 2, 4, 5, 1]

Document 对象参考手册 Python3 实例

AI 思考中...

4 篇笔记 写笔记

  1. #0

    萝卜国王

    142***[email protected]

    50

    一个简单的随机数字小游戏

    #!/usr/bin/python
    # -*- coding:utf-8 -*- 
    #随机数字小游戏
    import random
    i = 1
    a = random.randint(0,100)
    b = int( input('请输入0-100中的一个数字\n然后查看是否与电脑一样:'))
    while a != b:
     if a > b:
     print('你第%d输入的数字小于电脑随机数字'%i)
     b = int(input('请再次输入数字:'))
     else:
     print('你第%d输入的数字大于电脑随机数字'%i)
     b = int(input('请再次输入数字:'))
     i+=1
    else:
     print('恭喜你,你第%d次输入的数字与电脑的随机数字%d一样'%(i,b))

    萝卜国王

    142***[email protected]

    9年前 (2018年01月19日)
  2. #0

    小花花

    124***[email protected]

    33
    """源自鱼C论坛用户的猜数字游戏"""
    import random
    import re
    from sys import exit
    def main():
     time = 3
     count = 1
     num = 0
     dict = {'0': 5, '1': 10, '2': 20, '3': 50, '4': 100}
     print('猜数字')
     go = int(input('开始:1\n结束:0\n->'))
     while go != 1 and go != 0:
     print('Input 1 or 0.')
     go = int(input('开始:1\n结束:0\n->')) # 重复输入
     if go == 1:
     pass
     elif go == 0:
     exit()
     print('{LV0.新手}{LV1.简单}{LV2.一般}{LV3.困难}{LV4.噩梦}{LV5.地狱}')
     r = input('Level:')
     r = re.sub('\D', '', r) # 抽出数字
     if r.strip() == '': # 检查是否含有数字
     print('隐藏难度{LV6.调戏}')
     n = 1000
     time = 99
     else:
     n = dict.get(r, 500)
     secret = random.randint(1, n + 1) # 随机的范围 根据难度调整
     print('猜猜{1-%s}之间的数:' % n)
     while True: # 机会内循环即可,猜中了可以用break跳出循环
     print('一定是:' , end = '')
     num = input()
     if num.isdigit(): # 检查玩家输入是否有误,防止程序崩溃
     num = int(num)
     if num < 1:
     print('现在就放弃太可惜了')
     elif num > n:
     print('超出范围')
     elif num > secret:
     print('太大')
     elif num < secret:
     print('太小')
     else:
     if count == 1: # 算是奖励机制?
     print('棒')
     elif count == 2:
     print('赞')
     else:
     print('好')
     break
     time -= 1
     count += 1 # 奖励机制计数
     if time == 0:
     print('正确答案:%s' % secret)
     break
     else:
     print('还有[%s]次机会:' % time)
     else:
     print('要崩溃了!!!')
     print('游戏结束!')
    if __name__ == '__main__':
     main()

    小花花

    124***[email protected]

    7年前 (2019年07月08日)
  3. #0

    www.ono.wang

    by.***qq.com

    7

    该程序会在字符终端 1~24 之间的位置随机打印出一个星号 * ,并提示"请输入一个移动星号的指令(L/l or R/r)):",如果用户输入 L 并回车,星号就会向左移动一个字符的位置,并被重新输出;如果用户输入 R 并回车,星号则会向右移动一个字符的位置,程序会循环提示用户输入,直至用户输入 "EXIT",程序退出。

    import random
    class computer(object):
     def __init__(self):
     pass
     g_num = 0
     def ger_num(start,end):
     return random.randint(start,end)
     def contrl(ctl_str):
     global g_num
     if ctl_str == 'l' or ctl_str == 'L':
     g_num -= 1
     if g_num < 0:
     g_num = 23
     elif ctl_str == 'r' or ctl_str == 'R':
     g_num += 1
     if g_num > 23:
     g_num = 0
     return g_num
     @staticmethod
     def print_space(space_num):
     print_content = ['-']*24
     print_content = ''.join(print_content)
     l_content = list(print_content)
     l_content[space_num] = '*'
     l_content = ''.join(l_content)
     print(l_content)
    if __name__ == '__main__':
     #生成随机数,确定星号的位置
     g_num = computer.ger_num(0,24)
     computer.print_space(g_num)
     while True:
     ctrl_str = input("请输入移动星星的指令(L/l or R/r):")
     if ctrl_str == 'EXIT' or ctrl_str == 'exit':
     break
     g_num = computer.contrl(ctrl_str)
     computer.print_space(g_num)

    www.ono.wang

    by.***qq.com

    7年前 (2019年11月05日)
  4. #0

    Maria

    130***[email protected]

    58

    产生一个 1 到 10 的随机整数:

    random.randint(1,10)

    产生一个 0 到 1 的随机浮点数:

    random.random()

    产生一个 1.1 到 5.4 之间的随机浮点数:

    random.uniform(1.1, 5.4) 

    从序列中随机选取一个元素:

    random.choice(' ')

    生成从 1 到 100 间隔为 2 的随机整数:

    random.randrange(1,100,2)

    Maria

    130***[email protected]

    6年前 (2020年08月05日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /