GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.runoob.com — Python3 divmod() | 菜鸟教程
Python 3 教程
Python3 教程
Python3 简介
Python3 环境搭建
Python3 Pycharm
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 PyQtPython3 divmod() 函数Python divmod() 函数接收两个数字类型(非复数)参数,返回一个包含商和余数的元组(a // b, a % b)。 在 python 3.x 版本该函数不支持复数。 函数语法divmod() 函数接受两个参数,通常是两个数字,并返回一个包含两个值的元组。第一个值是第一个参数除以第二个参数的商(即整数部分),第二个值是余数。 divmod(a, b) 参数说明:
如果参数 a 与 参数 b 都是整数,函数返回的结果相当于 (a // b, a % b)。 如果其中一个参数为浮点数时,函数返回的结果相当于 (q, a % b),q 通常是 math.floor(a / b),但也有可能是 1 ,比小,不过 q * b + a % b 的值会非常接近 a。 如果 a % b 的求余结果不为 0 ,则余数的正负符号跟参数 b 是一样的,若 b 是正数,余数为正数,若 b 为负数,余数也为负数,并且 0 <= abs(a % b) < abs(b)。 实例
>>> divmod(7, 2) (3, 1) >>> divmod(8, 2) (4, 0) >>> divmod(8, -2) (-4, 0) >>> divmod(3, 1.3) (2.0, 0.3999999999999999) divmod() 函数的应用场景divmod() 在处理时间转换、分页计算等场景中非常有用。 1、时间转换 例如,将总秒数转换为小时、分钟和秒: 实例
total_seconds = 3661 hours, remainder = divmod(total_seconds, 3600) minutes, seconds = divmod(remainder, 60) print(f"{hours}小时 {minutes}分钟 {seconds}秒") # 输出:1小时 1分钟 1秒 2、分页计算 在分页系统中,divmod() 可以用来计算总页数和最后一页的记录数: 实例
total_items = 101 items_per_page = 10 pages, remainder = divmod(total_items, items_per_page) if remainder: pages += 1 print(f"总页数:{pages}") # 输出:总页数:11 divmod() 函数的注意事项divmod() 函数的第二个参数不能为 0,否则会引发 ZeroDivisionError 异常。 divmod() 函数返回的商和余数的类型取决于输入参数的类型。如果输入参数是整数,则返回的商和余数也是整数;如果输入参数是浮点数,则返回的商和余数也是浮点数。
AI 思考中...
点我分享笔记取消
分类导航
Advertisement
|
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |