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

要理解這個例子,您應該了解以下 Python 編程主題:
- Python 語法
- Python 數(shù)據(jù)類型
- Python 決策語句
python 程序中如何檢查奇數(shù)或偶數(shù)?
在這個初級 python 程序中,我們要檢查一個數(shù)字是偶數(shù)還是奇數(shù)。要檢查一個數(shù)是偶數(shù)還是奇數(shù),我們需要知道一個偶數(shù)和一個奇數(shù)。任何大于零的可被 2 整除的數(shù)都是偶數(shù)。例如,6 是偶數(shù),因為它可以被 2 整除。任何不能被 2 整除的數(shù)都是奇數(shù)數(shù)。比如 3 不能被 2 整除,2 是奇數(shù)。在這個 python 程序中,我們必須使用 python 中的 if 條件來實現(xiàn)這個邏輯。
使用 python 語言中的input方法接受用戶的數(shù)字后。在 python 中使用int將輸入字符串轉(zhuǎn)換為整數(shù)后,我們將數(shù)字保存在變量中。然后我們使用一個 Mod 運算符,用 2 給定一個數(shù),并檢查余數(shù)是否為零。使用if條件檢查余數(shù)是否為零,然后使用print功能,顯示一個數(shù)字是偶數(shù)。Else顯示的是奇數(shù)。
算法
STEP 1: 使用輸入函數(shù)接受一個字符串,并在 python 中使用 int 將其轉(zhuǎn)換為整數(shù)。然后將該值存儲在變量中。
STEP 2: 使用 mod 運算符檢查數(shù)字是否可被 2 整除。使用 if 條件檢查結(jié)果,并打印數(shù)字,即使條件得到滿足。
STEP 3: 使用elif 語句,使用 mod 運算符檢查數(shù)字不能被 2 整除,并將數(shù)字打印為奇數(shù)。
第 4 步:使用else語句并打印不是有效輸入的數(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ù)
URL網(wǎng)址:http://fisionsoft.com.cn/article/cosdsog.html


咨詢
建站咨詢
