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/zh-hant/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

發表回復

登錄後才能評論