新聞中心
創(chuàng)新互聯(lián)python教程:

要理解這個(gè)例子,您應(yīng)該了解以下 Python 編程主題:
- Python 語(yǔ)法
- Python 數(shù)據(jù)類型
- Python 決策語(yǔ)句
python 程序中如何檢查奇數(shù)或偶數(shù)?
在這個(gè)初級(jí) python 程序中,我們要檢查一個(gè)數(shù)字是偶數(shù)還是奇數(shù)。要檢查一個(gè)數(shù)是偶數(shù)還是奇數(shù),我們需要知道一個(gè)偶數(shù)和一個(gè)奇數(shù)。任何大于零的可被 2 整除的數(shù)都是偶數(shù)。例如,6 是偶數(shù),因?yàn)樗梢员?2 整除。任何不能被 2 整除的數(shù)都是奇數(shù)數(shù)。比如 3 不能被 2 整除,2 是奇數(shù)。在這個(gè) python 程序中,我們必須使用 python 中的 if 條件來實(shí)現(xiàn)這個(gè)邏輯。
使用 python 語(yǔ)言中的input方法接受用戶的數(shù)字后。在 python 中使用int將輸入字符串轉(zhuǎn)換為整數(shù)后,我們將數(shù)字保存在變量中。然后我們使用一個(gè) Mod 運(yùn)算符,用 2 給定一個(gè)數(shù),并檢查余數(shù)是否為零。使用if條件檢查余數(shù)是否為零,然后使用print功能,顯示一個(gè)數(shù)字是偶數(shù)。Else顯示的是奇數(shù)。
算法
STEP 1: 使用輸入函數(shù)接受一個(gè)字符串,并在 python 中使用 int 將其轉(zhuǎn)換為整數(shù)。然后將該值存儲(chǔ)在變量中。
STEP 2: 使用 mod 運(yùn)算符檢查數(shù)字是否可被 2 整除。使用 if 條件檢查結(jié)果,并打印數(shù)字,即使條件得到滿足。
STEP 3: 使用elif 語(yǔ)句,使用 mod 運(yùn)算符檢查數(shù)字不能被 2 整除,并將數(shù)字打印為奇數(shù)。
第 4 步:使用else語(yǔ)句并打印不是有效輸入的數(shù)字。
Python 源代碼
num = int(input("Enter any number: "))
if (num % 2) == 0: # check using mod operator and if that is true then print number is even
print(num, "it is an even number")
elif (num % 2) == 1: # Check using mod operator and if that not true then print number is odd
print(num, "it is an odd number")
else:
print("Error, this is not a valid input") # print the invalid input
輸出
Enter any number : 6
6 it is a even number. 分享題目:Python 程序:檢查用戶輸入值是奇數(shù)還是偶數(shù)
網(wǎng)站路徑:http://m.5511xx.com/article/cosdsog.html


咨詢
建站咨詢
