Python 模数运算符

像其他编程语言一样,Python 模数运算符做同样的工作来找到给定数字的模数。运算符是一种数学符号,用于对给定的两个数字执行不同的运算,如(+、-、* /)加法、减法、乘法和除法,以整数和浮点数的形式返回结果。运算符告诉编译器根据传递给给定数字的运算符符号执行某些操作。

Python 模数运算符是一个内置运算符,通过将第一个数字除以第二个数字来返回剩余的数字。它也被称为巨蟒模。在 Python 中,模数符号表示为百分比( % )符号。因此,它被称为余数运算符。

语法

下面是用第一个数除以第二个数得到余数的语法。


Rem = X % Y 

这里,X 和 Y 是两个整数,在两者之间使用模数(%),得到第一个数(X)除以第二个数(Y)的余数。

例如,我们有两个数字,24 和 5。我们可以用 24 % 5 之间的模或模算符得到余数。这里 24 除以 5,得到 4 作为余数,4 作为商。当第一个数可以被另一个数完全整除而不留下任何余数时,结果将是 0。

让我们编写一个程序,使用 Python 中的 While循环和 modulus)运算符来获取两个数字的余数。

Get_rem.py


while True: # if the while condition is true if block is executed
    a = input ('Do you want to continue or not (Y / N)? ')
    if a.upper() != 'Y':  # If the user pass 'Y', the following statement is executed.
        break

    a = int(input (' First number is: ')) # first number
    b = int(input (' Second number is: ')) # second number
    print(a, ' % ', b, ' = ', a % b) # perform a % b    
    print(b, ' % ', a, ' = ', b % a) # perform b % a

输出:

Do you want to continue or not (Y / N)? Y
First number is: 37
Second number is: 5
37 % 5 = 2
5 % 37 = 5

Do you want to continue or not (Y / N)? Y
First number is: 37
Second number is: 5
24 % 5 = 4
5 % 24 = 5

Do you want to continue or not (Y / N)? Y
First number is: 37
Second number is: 5
28 % 5 = 3
5 % 28 = 5

让我们编写一个程序,使用 Python 中的模数运算符来查找两个整数的余数。

修改 py


x = float(input ('First number: '))
y = float(input (' Second number: '))

res = x % y # store the remainder in res variable
print("Modulus of two float number is: ", x, "%", y, " = ", res, sep = " ")

输出:

First number: 40.5
 Second number: 20.5
Modulus of two float number is:  40.5 % 20.5 = 20.0

让我们编写一个程序,使用 Python 中的 While循环和 modulus)运算符来获取两个负数的余数。

修改 py


while True:
    x = input(' Do you want to continue (Y / N)? ')
    if x.upper() != 'Y':
        break

    # input two integer number and store it into x and y
    x = int(input (' First number: '))
    y = int(input (' Second number: '))

    print("Modulus of negative number is: ", x, "%", y, " = ", x % y, sep = " ")
    print("Modulus of negative number is: ", y, "%", x, " = ", y % x, sep = " ")

输出:

First number: -10
Second number: 3
Modulus of negative number is:  -10 % 3  =  2
Modulus of negative number is:  3 % -10  =  -7
 Do you want to continue (Y / N)? N

让我们编写一个程序,使用 Python 中的 fmod()函数来获取两个浮点数的余数。

Fmod.py


import math    # import math package to use fmod() function.
res = math.fmod(25.5, 5.5) # pass the parameters
print ("Modulus using fmod() is:", res)
ft = math.fmod(75.5, 15.5)
print (" Modulus using fmod() is:", ft)
# take two integer from the user
x = int( input( "First number is"))
y = int (input ("Second number is "))
out = math.fmod(x, y) # pass the parameters 
print("Modulus of two numbers using fmod() function is", x, " % ", y, " = ", out)  

输出:

Modulus using fmod() is: 3.5
 Modulus using fmod() is: 13.5
First number is 24
Second number is 5
Modulus of two numbers using fmod() function is 24  %  5  =  4.0

让我们编写一个 Python 程序,使用函数和 for循环来求 n 的模。

get main . py


def getRemainder(n, k):
    for i in range(1, n + 1):
        # Store remainder in the rem variable when i is divided by k number
        rem = i % k   
        print(i, " % ", k, " = ", rem, sep = " ")   

# use _name_ driver code
if __name__ == "__main__":

    # define the first number for displaying the number up to desired number.  
    n = int(input ("Define a number till that you want to display the remainder "))
    k = int( input (" Enter the second number ")) # define the divisor 

    # call the define function
    getRemainder(n, k)  

输出:

Define a number till that you want to display the remainder 7
 Enter the second number 5
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0
6 % 5 = 1
7 % 5 = 2

让我们编写一个程序来演示 Python 中的 mod()函数。

Mod_fun.py


import numpy as np # import numpy package
x = np.array([40, -25, 28, 35]) # define first array
y = np.array([20, 4, 6, 8]) # define second array
# call mod() function and pass x and y as the parameter
print("The modulus of the given array is ", np.mod (x, y))

输出:

The modulus of the given array is [0 3 4 3]

正如我们在上面的程序中看到的,x 和 y 变量保存数组。之后,我们使用 mod()函数传递 x 和 y 作为数组参数,将第一个数组(x)除以第二个数组(y),然后返回剩余的数字。

让我们考虑一个程序,从 Python 库中导入一个 numpy 包,然后用余数函数得到 Python 中的模数。

号 py


import numpy as np # import numpy package as np
# declaration of the variables with their values
num = 38 
num2 = 8
res = np.remainder(num, num2) # use np.remainder() function
print( "Modulus is", num, " % ", num2, " = ", res) # display modulus num % num2

输出:

Modulus is 38 % 8 = 6

在 Python 中,当一个数被零除时,它会抛出一个异常,这个异常被称为零除错误。换句话说,当一个数可以被一个零除数整除时,它会返回一个异常。因此,如果我们想从 Python 模数运算符中移除异常,除数不应该为零。

让我们编写一个程序来演示模数运算符中的 Python 异常。

除了. py


x = int(input (' The first number is: '))
y = int(input (' The second number is: '))

# display the exception handling
try: # define the try
    print (x, ' % ', y, ' = ', x % y)
except ZeroDivisionError as err: # define the exception 
    print ('Cannot divide a number by zero! ' + 'So, change the value of the right operand.' )    

输出:

The first number is: 24
The second number is: 0
Cannot divide a number by zero! So, change the value of the right operand.

正如我们在上面的结果中看到的,它显示,“不能用零除一个数!所以,改变右操作数的值。因此,我们可以说,当我们将第一个数除以 0 时,它会返回一个异常。


原创文章,作者:NRRCY,如若转载,请注明出处:https://www.506064.com/n/127206.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
NRRCY的头像NRRCY
上一篇 2024-10-03 23:13
下一篇 2024-10-03 23:13

相关推荐

  • Python计算阳历日期对应周几

    本文介绍如何通过Python计算任意阳历日期对应周几。 一、获取日期 获取日期可以通过Python内置的模块datetime实现,示例代码如下: from datetime imp…

    编程 2025-04-29
  • Python中引入上一级目录中函数

    Python中经常需要调用其他文件夹中的模块或函数,其中一个常见的操作是引入上一级目录中的函数。在此,我们将从多个角度详细解释如何在Python中引入上一级目录的函数。 一、加入环…

    编程 2025-04-29
  • 如何查看Anaconda中Python路径

    对Anaconda中Python路径即conda环境的查看进行详细的阐述。 一、使用命令行查看 1、在Windows系统中,可以使用命令提示符(cmd)或者Anaconda Pro…

    编程 2025-04-29
  • Python周杰伦代码用法介绍

    本文将从多个方面对Python周杰伦代码进行详细的阐述。 一、代码介绍 from urllib.request import urlopen from bs4 import Bea…

    编程 2025-04-29
  • Python列表中负数的个数

    Python列表是一个有序的集合,可以存储多个不同类型的元素。而负数是指小于0的整数。在Python列表中,我们想要找到负数的个数,可以通过以下几个方面进行实现。 一、使用循环遍历…

    编程 2025-04-29
  • Python清华镜像下载

    Python清华镜像是一个高质量的Python开发资源镜像站,提供了Python及其相关的开发工具、框架和文档的下载服务。本文将从以下几个方面对Python清华镜像下载进行详细的阐…

    编程 2025-04-29
  • Python程序需要编译才能执行

    Python 被广泛应用于数据分析、人工智能、科学计算等领域,它的灵活性和简单易学的性质使得越来越多的人喜欢使用 Python 进行编程。然而,在 Python 中程序执行的方式不…

    编程 2025-04-29
  • Python字典去重复工具

    使用Python语言编写字典去重复工具,可帮助用户快速去重复。 一、字典去重复工具的需求 在使用Python编写程序时,我们经常需要处理数据文件,其中包含了大量的重复数据。为了方便…

    编程 2025-04-29
  • 蝴蝶优化算法Python版

    蝴蝶优化算法是一种基于仿生学的优化算法,模仿自然界中的蝴蝶进行搜索。它可以应用于多个领域的优化问题,包括数学优化、工程问题、机器学习等。本文将从多个方面对蝴蝶优化算法Python版…

    编程 2025-04-29
  • python强行终止程序快捷键

    本文将从多个方面对python强行终止程序快捷键进行详细阐述,并提供相应代码示例。 一、Ctrl+C快捷键 Ctrl+C快捷键是在终端中经常用来强行终止运行的程序。当你在终端中运行…

    编程 2025-04-29

发表回复

登录后才能评论