該計劃的目標是:
- 驗證輸入格式,日期范圍不應超過 2 個月
- 無輸入/無效輸入 -> 根據當月日期回傳當前月的上半月或下半月
- 上半年是從第 1 天到第 15 天,下半年是從第 16 天到月底
硬代碼(將是第一個代碼片段)以正確的輸出按預期作業,但是第二個代碼片段中的日期驗證不會跳轉到 except 塊中指示的方法,這導致我出現問題并且不顯示正確的輸出.
import os, sys
import datetime as dt
if __name__ == '__main__':
validate_range('2003/12/23', '2003/12/22')
validate_range('2003/10/23', '2003/11/22')
validate_range('2003/12/23', '2003/10/22')
validate_range('2003/7/23', '2003/10/22')
具有正確輸出的代碼段(不檢查日期是否格式正確):
def validate_range(first_date, second_date):
start_date = dt.datetime.strptime(first_date, '%Y/%m/%d') # Get first date
end_date = dt.datetime.strptime(second_date, '%Y/%m/%d') # Get second date
num_months = (end_date.year - start_date.year) * 12 (
end_date.month - start_date.month) # Get year/month within 2 months
if num_months >= 0 and num_months <= 2:
print("In Range")
else:
current_day = dt.datetime.today().day
if current_day >= 1 and current_day <= 15:
print("First half")
if current_day >= 16 and current_day <= 32:
print("Second half")
正確的輸出:
In Range
In Range
First half
First half
不顯示正確輸出的代碼片段(帶有日期驗證):
def read_args(first_date, second_date):
try:
start_date = dt.datetime.strptime(first_date, '%Y/%m/%d') # Get first date
end_date = dt.datetime.strptime(second_date, '%Y/%m/%d') # Get second date
v_range(start_date, end_date)
except:
w_range()
def v_range(first_date, second_date):
num_months = (second_date.year - first_date.year) * 12 (
second_date.month - first_date.month) # Get year/month within 2 months
if num_months >= 0 and num_months <= 2:
print("In Range")
def w_range():
current_day = dt.datetime.today().day
if current_day >= 1 and current_day <= 15:
print("First half")
if current_day >= 16 and current_day <= 32:
print("Second half")
輸出:
In Range
In Range
uj5u.com熱心網友回復:
保持您對try / except,的使用可能需要一些改進,但此示例表明這是可能的:
import os, sys
import datetime as dt
def read_args(first_date, second_date):
try:
start_date = dt.datetime.strptime(first_date, '%Y/%m/%d') # Get first date
end_date = dt.datetime.strptime(second_date, '%Y/%m/%d') # Get second date
result = v_range(start_date, end_date)
except:
pass
# w_range()
def v_range(first_date, second_date):
num_months = (second_date.year - first_date.year) * 12 (
second_date.month - first_date.month) # Get year/month within 2 months
if num_months >= 0 and num_months <= 2:
print("In Range")
else:
w_range()
def w_range():
current_day = dt.datetime.today().day
if current_day >= 1 and current_day <= 15:
print("First half")
if current_day >= 16 and current_day <= 32:
print("Second half")
if __name__ == '__main__':
read_args('2003/12/23', '2003/12/22')
read_args('2003/10/23', '2003/11/22')
read_args('2003/12/23', '2003/10/22')
read_args('2003/7/23', '2003/10/22')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409569.html
標籤:
