Python运算符 //、/、% 详解与区别:从入门到精通

【Python基础篇】你了解python中运算符吗 你了解python中运算符吗?? 阅读详情
AI摘要

本文深入解析Python中//(整除)、/(除法)和%(取模)三种算术运算符。介绍了它们的功能、语法、特点及区别,阐述了在精确计算、分页计算、判断奇偶性等不同场景的应用,还提及负数运算、浮点数精度等常见问题及性能比较。

包含编程籽料、学习路线图、爬虫代码、安装包等!【点击领取】

1. 概述
在Python编程中,//(整除)、/(除法)和%(取模)是三种常用的算术运算符。虽然它们都与除法相关,但功能和使用场景却大不相同。本文将深入解析这三种运算符的区别、使用方法和实际应用场景。

2. 运算符详解
2.1 除法运算符 /
功能:执行标准的除法运算,返回浮点数结果(即使在整数相除时)。

语法:

a / b

示例:

print(10 / 3)   # 输出: 3.3333333333333335
print(9 / 2)    # 输出: 4.5
print(10 / 2)   # 输出: 5.0 (注意结果是浮点数)

特点:

总是返回浮点数

适用于需要精确除法结果的场景

Python 3.x中/的行为与Python 2.x不同(Python 2.x中整数相除会截断)

2.2 整除运算符 //
功能:执行地板除法(floor division),返回不大于结果的最大整数。

语法:

a // b

示例:

print(10 // 3)   # 输出: 3
print(9 // 2)    # 输出: 4
print(-10 // 3)  # 输出: -4 (注意负数的结果)
print(10.0 // 3) # 输出: 3.0 (操作数有浮点数则返回浮点数)

特点:

结果向负无穷方向取整

如果操作数中有浮点数,结果也是浮点数

常用于需要整数结果的场景,如分页计算

2.3 取模运算符 %
功能:返回除法的余数。

语法:

a % b

示例:

print(10 % 3)    # 输出: 1
print(9 % 2)     # 输出: 1
print(-10 % 3)   # 输出: 2 (注意负数的结果)
print(10.5 % 3)  # 输出: 1.5 (支持浮点数)

特点:

结果符号与除数相同

常用于判断奇偶性、循环索引等场景

与//运算符关系:a == (a // b) * b + a % b

3. 三者的区别对比
在这里插入图片描述
4. 实际应用场景
4.1 / 的应用
场景:需要精确计算时

# 计算平均值
grades = [85, 90, 78, 92]
average = sum(grades) / len(grades)
print(average)  # 输出: 86.25

4.2 // 的应用
场景1:分页计算

total_items = 103
items_per_page = 10
total_pages = (total_items + items_per_page - 1) // items_per_page
print(total_pages)  # 输出: 11

场景2:时间转换

seconds = 3661
minutes = seconds // 60
remaining_seconds = seconds % 60
print(f"{minutes}分{remaining_seconds}秒")  # 输出: 61分1秒

4.3 % 的应用
场景1:判断奇偶性

number = 7
if number % 2 == 0:
    print("偶数")
else:
    print("奇数")  # 输出: 奇数

场景2:循环缓冲区索引

buffer_size = 5
index = 0
for i in range(10):
    index = (index + 1) % buffer_size
    print(index, end=" ")  # 输出: 1 2 3 4 0 1 2 3 4 0

5. 常见问题与陷阱
5.1 负数运算

print(-10 // 3)  # 输出: -4 (不是-3)
print(-10 % 3)   # 输出: 2 (不是-1)

解释:Python的//向负无穷取整,%的结果符号与除数相同。

5.2 浮点数精度问题

print(0.1 + 0.2 == 0.3)  # 输出: False
print(0.1 % 0.1)         # 输出: 0.0
print(0.2 % 0.1)         # 输出: 0.0 (但实际可能因浮点精度有微小差异)

建议:对浮点数使用math.isclose()进行比较。

5.3 除数为零

try:
    print(10 // 0)
except ZeroDivisionError as e:
    print(f"错误: {e}")  # 输出: 错误: integer division or modulo by zero

6. 性能比较
在大多数情况下,三种运算符的性能差异可以忽略不计。但在极端性能敏感场景(如大规模数值计算):

// 通常比 / 稍快(因为不需要处理浮点数)

% 的性能与 // 相当

对于固定除数的取模,编译器可能优化为位运算(当除数是2的幂时)

7. 总结
/:当你需要精确的除法结果时使用

//:当你需要整数结果或向下取整时使用

%:当你需要余数或周期性索引时使用

理解这三个运算符的区别和适用场景,可以帮助你写出更高效、更准确的Python代码。

最后:
希望你编程学习上不急不躁,按照计划有条不紊推进,把任何一件事做到极致,都是不容易的,加油,努力!相信自己!

文末福利
最后这里免费分享给大家一份Python全套学习资料,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。

包含编程资料、学习路线图、源代码、软件安装包等!【点击这里】领取!
① Python所有方向的学习路线图,清楚各个方向要学什么东西
② 100多节Python课程视频,涵盖必备基础、爬虫和数据分析
③ 100多个Python实战案例,学习不再是只会理论
④ 华为出品独家Python漫画教程,手机也能学习

在这里插入图片描述

关于python的基本使用语法(完整版) Python是一门简单易学、功能强大的高级编程语言,具有语法简洁、可读性强、跨平台支持好等特点。它由 Guido van Rossum 于 1991 年开发,目前广泛应用于数据分析、人工智能、Web 开发、自动化脚本、爬虫等多个领域。定义:在 Python 中,变量的类型是动态的,有时我们需要将一种类型的数据转换为另一种类型,这就是类型转换。条件语句可以让程序根据不同的情况执行不同的代码,常用于判断、分支、选择,比如“如果成绩大于60就及格,否则不及格函数是指一段可以被重复调用的可执行代码块。 阅读详情

相关推荐

Python中的双斜杠(//)运算符的含义和用法

总结一下,双斜杠(//)运算符是Python中用于执行整数除法的运算符。这意味着,无论除法操作的结果是否是一个整数,双斜杠运算符都会返回一个整数。双斜杠(//)是Python中的一个运算符,用于执行整数除法操作。在本文中,我们将详细介绍双斜杠运算符的含义和功能,以及它在实际编程中的应用。由于双斜杠运算符执行整数除法,它返回了结果的整数部分。在上面的示例中,我们使用单斜杠运算符执行了10除以3的浮点数除法,返回结果的小数部分。由于双斜杠运算符执行整数除法,它返回了结果的整数部分,即3。的值时,输出结果为3。

学习使你进步。 1万+

python中“//”表示什么意思

python中“//”是一个算术运算符,表示整数除法,它可以返回商的整数部分(向下取整)。具体用法如:【a = 10 b = 5 c = a//b 】,结果输出整数2。 a = 10 b = 4 c = a // b c 输出为2 注意:Python2.x 里,整数除整数,只能得出整数。如果要得到小数部分,把其中一个数改成浮点数即可。 a = 10 b = 4.0 c = a // b c 输出为2.0 ...

weixin_44217936的博客 4万+

Day14:整除运算

整除运算是指对两个整数进行除法运算,返回结果的整数部分,舍弃余数。在Python中,整除运算使用运算符 `//` 表示。

AIGC 1837

一分钟看懂Python中的//, /, %的作用和区别

在python中,我们经常需要对数字进行一些基本的运算,比如加、减、乘、除等。为了实现这些运算,我们可以使用一些特殊的符号,称为算术运算符。例如,我们可以用+号表示加法,用-号表示减法,用*号表示乘法,用/号表示除法等。这些运算符都遵循一定的语法规则和优先级顺序,我们可以用它们来构建复杂的数学表达式。

xjt921122的博客 9728

Python编程从入门到精通:源代码剖析与实践

函数是执行特定任务的代码块,在Python中定义函数的语法如下:当Python程序运行过程中发生错误时,会产生异常。Python提供了很多内置的异常类型来处理不同的错误情况,如ValueErrorIndexErrorKeyError等。掌握常见的异常类型对于诊断问题和编写健壮的代码非常有帮助。# 示例代码展示常见的内置异常try:# 假设这里有一个错误的索引操作# 输出IndexError异常信息除了内置的异常,开发者也可以定义自己的异常类,以适应特定的错误处理需求。

weixin_32445049的博客 1086

LangChain + PlayWright实战:5分钟搞定网页自动化测试(附完整代码)

本文详细介绍了如何利用LangChain与PlayWright构建智能网页自动化测试系统。通过环境配置、核心架构设计、实战Agent构建及性能优化等步骤,开发者可以快速实现高效的Web操作自动化,提升测试效率。文章还提供了完整代码示例和典型问题解决方案。

weixin_27791839的博客 251

【Python学习】Python中的“//“、“/“、“%“运算符详解与区别

在实际应用中,选择使用 //, /, %运算符取决于具体的需求。理解它们的特性和区别,有助于在不同场景中选择合适的运算符。课件,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。除了单独使用//,/, %运算符外,还可以与赋值运算符结合使用,形成复合运算符。在进行除法运算时,特别是涉及浮点数时,可能会遇到精度丢失的问题。在上述例子中,由于浮点数的二进制表示方式,计算结果不是精确的。在实际开发中,为了避免这种问题,可以使用。在进行除法或取余运算时,如果除数为零,将导致。

zhang120529的博客 9774

gesp c++ 五级知识点

gesp c++ 五级知识点

MMD.然大大 2039

Python中的//, /, % 运算符详解与区别

在本文中,深入探讨了Python中整除运算符//、除法运算符、取余运算符的特性和区别,以及在实际应用中的选择原则。了解它们的使用场景,可以更灵活地应对不同的数学计算需求。运算符适用于需要保留小数部分的计算,//运算符则得到整数结果,适用于向下取整的情况,而运算符用于获取除法的余数,方便判断整除关系。在选择运算符时,还需关注浮点数运算的精度问题以及除数为零的异常情况,保证代码的健壮性。最终,灵活运用这些运算符,将有助于编写更具可读性和高效性的数学计算代码。

涛哥聊Python 1万+

PX4|Gazebo模型加载失败排查指南:从环境变量到资源路径的全面解析

本文针对PX4与Gazebo联合仿真中常见的'Unable to get model name'错误,提供了从环境变量配置、资源路径排查到网络访问问题的全面解决方案。详细解析了GZ_SIM_RESOURCE_PATH等关键变量的作用与设置方法,并给出了离线模型库部署等一劳永逸的修复指南,帮助开发者彻底解决无人机模型加载失败问题。

weixin_29243063的博客 1236

群晖设置公网ipv6方式域名解析访问

群晖、IPV6、域名解析

爬山虎的博客 2万+

Python中__、_、%运算符的深度解析与实战应用

(加)、(减)、(乘)(除)、//(整除)、(取模)**(幂运算)括号()最高幂运算**乘除//加减提供精确的浮点数结果//用于需要整数结果的场景解决余数相关的问题print(5 / 2) # 2.5(经典除法)print(5 // 2) # 2(整除)print(5 % 2) # 1(取模)运算符结果类型数学含义float精确除法//int向下取整除法int除法余数用于精确计算,//用于整数结果,用于余数注意负数运算时的特殊行为组合使用divmod()

ztt123654的博客 1375

分布式优化 (Distributed Optimization) 算法详解及案例分析

分布式优化是一种将优化问题分解为多个子问题并在多个计算节点上并行求解的方法。其目标是通过分布式计算资源高效地求解大规模优化问题。

闲人编程的博客 2734

python //、/、%

python2中的地板除/,是取整数位。 3/2=1 3/2.0=1.5 在pyhon3中/是真除法。 3/2=1.5 如果想在python3使用地板除,是// 3//2=1 %表示求余数 5%2=1

qq_26529803的博客 1万+

UDPProbe UDP端口存活探测(发送特征包+响应分析)、UDP服务识别

qDebug() << "收到响应:" << ip.toString() << ":" << port << " 服务:" << serviceName << " 响应长度:" << response.size();qDebug() << "开始探测:" << targetIp << ":" << port << " 超时时间:" << timeout << "ms";qInfo() << "\n==================== UDP探测结果 ====================";

寒寒豆豆软件公司的博客 163

精通 Android NDK/JNI:从入门到精通实战与面试精粹

在Android开发中,

郑伟强dev的专栏 155

Python入门:Python3 运算符全面学习教程

Python入门:Python3 运算符全面学习教程,在 Python 编程中,运算符是处理数据和变量的基础工具。掌握各种运算符的用法,能帮助我们更高效地编写代码、处理逻辑。本文是 Python3 运算符的学习教程,详细讲解了算术、比较、赋值、位运算、逻辑、成员、身份共七类运算符及优先级。算术运算符含加减乘除等基础运算;比较运算符返回布尔值判断对象关系;赋值运算符含复合赋值及 Python3.8 新增的海象运算符;位运算符基于二进制计算;逻辑运算符组合布尔表达式;成员运算符判断值是否在序列中;身份运算符比较

不踩坑,不知道坑有多深;不总结,踩过的坑白踩。 22万+

【2025软考高级架构师】基础知识部分——6、软件架构设计

(1)架构是对系统的抽象(2)架构由多个结构组成(3)任何软件都存在架构(4)元素及其行为的集合构成架构的内容(5)架构具有“基础”性(6)架构隐含有“决策”

qq837993702的博客 1万+

Python运算符学习五层境界:从入门到精通

运算符是编程语言中的基础概念,用于执行各种数学和逻辑运算。在Python中,运算符分为算术、比较、逻辑、位运算等多种类型,每种都有其特定的语法和优先级规则。理解运算符的工作原理对于编写高效、可靠的代码至关重要,特别是在算法实现和性能优化场景中。Python运算符具有短路求值、运算符重载等高级特性,掌握这些特性可以显著提升代码质量。本文通过五层学习境界模型,系统讲解从基础运算符使用到位运算优化等进阶技巧,帮助开发者构建完整的运算符知识体系。

weixin_32306957的博客 338

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

上一篇: 【Python爬虫教程】快速精准抓取网页数据
下一篇: Python线程使用详解:从基础到高级实战
Python_trys
博客等级 码龄2年 4508粉丝 377原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址