Python 取模运算符

Python 取模运算符

与其他编程语言类似,Python的模运算符也执行相同的工作,用于计算给定数值的模数。该运算符是一个数学符号,用于执行不同的操作,如加法,减法,乘法和除法,对给定的两个数返回整数和浮点数的结果。运算符根据传递给定数的运算符符号,告诉编译器执行特定的动作。

Python 取模运算符

取模运算符

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

语法

以下是通过将第一个数除以第二个数来获得余数的语法。

Rem = X % Y 

这里X和Y是两个整数,而模(%)用在它们之间以获得第一个数(X)除以第二个数(Y)所得的余数。

例如,我们有两个数,24和5。我们可以使用模运算符24%5来获得余数。在这里,24除以5余数为4,商为4。当第一个数被另一个数整除时,没有余数,结果为0。例如,我们有两个数,20和5。我们可以使用模运算符20%5来获得余数。在这里,20除以5余数为0,商为4。

使用while循环获取两个整数数的模

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

Get_rem.py

while True:           # here, if the while condition is true then if block will be executed  
    a = input ('Do you want to continue or not (Y / N)? ')  
    if a.upper() != 'Y':     # here, If the user pass 'Y', the following statement is executed.  
        break  
    a = int(input (' First number is: '))    # here, we are taking the input for first number  
    b = int(input (' Second number is: ')) 
     # Here, we are taking the input for second number  
    print("The result after performing modulus operator is: ", a, ' % ', b, ' = ', a % b) 
# Here, we are performing the modulus a % b      
    print("The result after performing modulus operator is:", b, ' % ', a, ' = ', b % a) 
# Here, we are performing the modulus b % a  

输出:

Do you want to continue or not (Y / N)? Y
First number is: 37
Second number is: 5
The result after performing modulus operator is: 37 % 5 = 2
The result after performing modulus operator is: 5 % 37 = 5
Do you want to continue or not (Y / N)? Y
First number is: 37
Second number is: 5
The result after performing modulus operator is: 24 % 5 = 4
The result after performing modulus operator is: 5 % 24 = 5
Do you want to continue or not (Y / N)? Y
First number is: 37
Second number is: 5
The result after performing modulus operator is: 28 % 5 = 3
The result after performing modulus operator is: 5 % 28 = 5

获取两个浮点数的模数

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

Mod.py

x = float(input ('First number: '))       
# Here, we are taking the input for the first number  
y = float(input (' Second number: '))     
# Here, we are taking the input for the second number  
res = x % y       # Here, we are storing the remainder in a new 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循环和模数(%)运算符获得两个负数的余数。

Mod.py

while True:  
    x = input(' Do you want to continue (Y / N)? ')  
    if x.upper() != 'Y':  
        break  
    # Here, we are taking input two integer number and store it into x and y  
    x = int(input (' First number: '))  
    # Here, we are taking the input for the first number
    y = int(input (' Second number: '))  
    # Here, we are taking the input for the 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

使用fmod()函数获取两个数字的模数

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

Fmod.py

import math    # here, we are importing the math package to use fmod() function.  
res = math.fmod(25.5, 5.5)    # here, we are passing the parameters  
print ("Modulus using fmod() is:", res)  
ft = math.fmod(75.5, 15.5)  
print (" Modulus using fmod() is:", ft)  
# Here, we are taking two integers from the user  
x = int( input( "First number is"))
# Here, we are taking the input for the first number   
y = int (input ("Second number is "))  
# Here, we are taking the input for the second number
out = math.fmod(x, y)     # here, we are passing 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

使用函数求n个数字的模

让我们编写一个Python程序,在函数和for循环中找出n个数字的模。

getRemainder.py

def getRemainder(n, k):     # here, we are creating a function
    for i in range(1, n + 1):     # here, we are declaring a for loop
    # Here, we are storing remainder in the rem variable when i is divided by k number  
        rem = i % k     
        print(i, " % ", k, " = ", rem, sep = " ")     
# Here, the code for use _name_ driver   
if __name__ == "__main__":    
   # Here, we 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 "))    # here, we are defining the divisor     
    # Here, we are calling 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

使用mod()函数获取给定数组的模数

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

Mod_fun.py

import numpy as np      # here, we are importing the numpy package  
x = np.array([40, -25, 28, 35])     # here, we are define the first array  
y = np.array([20, 4, 6, 8])      # here, we are define the second array  
# Here, we are calling the 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),并返回余数。

使用numpy获取两个数的模

让我们考虑一个程序,从Python库中导入 numpy 包,然后使用remainder函数来在Python中获取模。

Num.py

import numpy as np      # here, we are importing the numpy package as np
# Here, we are giving the declaration of the variables with their values  
num = 38        # here, we are initializing the num variable
num2 = 8         # here, we are initializing the num2 variable
res = np.remainder(num, num2)     # here, we are using the np.remainder() function  
print("Modulus is", num, " % ", num2, " = ", res) 
# Here, we are displaying the modulus num % num2  

输出:

Modulus is 38 % 8 = 6

Python取模运算符中的异常

在Python中,当一个数被零除时,会抛出一个异常,这个异常被称为 ZeroDivisionError 。换句话说,当一个数可以被零除时,它会返回一个异常。因此,如果我们想要在Python取模运算符中去除异常,除数就不能为零。

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

Except.py

x = int(input (' The first number is: '))      
# Here, we are taking the input for the first number
y = int(input (' The second number is: '))  
# Here, we are taking the input for the second number
# Here, we are displaying the exception handling  
try:            # here, we are defining the try block  
    print (x, ' % ', y, ' = ', x % y)  
except ZeroDivisionError as err:       # here, we are defining the exception block   
    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.

如上所示,结果显示:

无法将一个数除以零!因此,请更改右操作数的值

因此,我们可以说,当我们将第一个数除以零时,会返回一个异常。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程