在這個簡單的 python 程序中,我們必須檢查 python 中的有效日期。這是一個初級 python 程序。
要理解這個例子,您應該了解以下 Python 編程主題:
- Python 語法
- Python 安裝和設置
- Python 決策語句
在這個初級 python 程序中,我們需要檢查給定的日期是有效還是無效。檢查日期是否有效就是檢查日期和月份是否正確。要檢查月份有效性,請檢查月份是否在數字 1 和 12 之間。如果大於 12,則日期無效。通過一些條件來檢查一天是否有效,比如一個月是 1、3、5、7、8、10 還是 12。那麼當天的最大值是 31;否則無效。
如果月份是 4 或 6 或 9 或 11,那麼一天的最大值是 30。如果日期超過 30,則日期無效。最後,我們通過使用帶有年份的 mod 運算符來檢查年份是否是閏年。然後用 4 或 400 等於零和年模式 100 不等於零[請參考閏年 python 程序了解更多細節]如果是閏年,那麼 max 將是 28 否則將是 27 如果輸入的日期不是驗證閏年,打印日期無效。
為了在 python 編程語言中應用這種邏輯,我們使用split date
函數分別分割月、日和年,然後使用int()
數據類型將它們轉換為整數。現在我們使用 python 中的 if 條件和elif
條件來檢查上面討論的所有條件,以檢查日期是否有效。
STEP 1: 接受用戶使用輸入法輸入的日期為使用 python 方法中日期的日期。
步驟 2: 使用分隔符/將日期拆分為 dd 和 mm 和 yy 。
步驟 3: 使用 python 語言中的int()
數據類型,將 dd 和 mm 和 yy 的值分配到各自的變量中。
第四步:使用if
條件,我們檢查月份是 1 或 3 或 5 或 7 或 8 或 10 或 12,如果是這樣,則將當天的最大值指定為 31。
STEP 5: 使用elif
我們檢查月份是 4 或 6 或 9 或 11,然後將最大值指定為 30。
第 6 步:通過將 mod 取為 yy%4==0 和 yy0,使用if
條件檢查一年是否是閏年!=0 或 yy@0==0。那麼這是閏年,所以將最大值指定為 29。
第七步:使用else
,這不是閏年,所以最大值是 28。
STEP 8: 使用if
條件檢查月份有效性,檢查月份小於 1 或大於 12 則打印日期無效。
STEP 9: 使用elif
檢查日期小於 1 或大於我們的最大值打印日期無效使用 python 語言基礎。
STEP 10: 使用 python 語言的 else 語句打印輸入的日期是否有效。
date=input("Enter the date: ")
dd,mm,yy=date.split('/') # splitting the date to day month and year
dd=int(dd)
mm=int(mm)
yy=int(yy)
if(mm==1 or mm==3 or mm==5 or mm==7 or mm==8 or mm==10 or mm==12):
max=31
elif(mm==4 or mm==6 or mm==9 or mm==11): # checking for the day is valid or not, finding max value
max=30
elif(yy%4==0 and yy0!=0 or yy@0==0): # leap year check
max=29
else:
max=28
if(mm<1>12):
print("Date is invalid.")
elif(dd<1>max):
print("Date is invalid.")
else:
print("Date you entered is valid")
Enter the date : 5/7/2016
Date you entered is valid
原創文章,作者:Y49E3,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/127315.html