[英]Error in checking validity of month in python function
month_names=["january","february","march","april",
"may","june","july","august","september","october","november","december"]
day_in_month=[31,28,31,30,31,30,31,31,30,31,30,31]
date =" "
a,b=date.split(" ")
b=int()
x=False
def is_a_valid_date(date):
global x
for i in range(len(month_names)):
if a==month_names[i]:
if b<=day_in_month[i]:
x=True
print("h")
return x
print(is_a_valid_date("february 21"))
ValueError:沒有足夠的值來解包(預期 2,得到 1)
嘗試檢查輸入中的給定字符串是否是 month_names 中提到的有效月份如果與 day_in_month 中的天數相比,其后面的日期也有效
你應該避免使用 global 並且你根本不使用你的參數date
!
month_names = [
"january","february","march","april",
"may","june","july","august","september","october","november","december"
]
day_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
def is_a_valid_date(date):
month, day = date.split(" ") # split with space the month and day
month_index = month_names.index(month) # find the index of the month_index from the month_names
day_as_int = int(day) # convert the day to int for compering
return day_as_int <= day_in_month[month_index] # check if it bigger
print(is_a_valid_date("february 29")) # False
print(is_a_valid_date("february 28")) # True
如果你想捕捉大寫和磨損輸入等邊緣情況:
month_names = [
"january","february","march","april",
"may","june","july","august","september","october","november","december"
]
day_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
# make it lower case
def is_a_valid_date(date):
try:
month, day = date.lower().split(" ") # split with space the month and day
month_index = month_names.index(month) # find the index of the month_index from the month_names
day_as_int = int(day) # convert the day to int for compering
return day_as_int > 0 and day_as_int <= day_in_month[month_index] # check if it bigger
except ValueError:
return False
print(is_a_valid_date("february 29")) # False
print(is_a_valid_date("february 28")) # True
print(is_a_valid_date("febGuary 28")) # False
print(is_a_valid_date("february 0")) # False
print(is_a_valid_date("February 1")) # True
print(is_a_valid_date("February1")) # False
print(is_a_valid_date("February gasf")) # False
print(is_a_valid_date("")) # False
嘗試這個:
month_names=["january","february","march","april",
"may","june","july","august","september","october","november","december"]
day_in_month=[31,28,31,30,31,30,31,31,30,31,30,31]
x=False
def is_a_valid_date(date):
global x
a,b=date.split(" ")
for i in range(len(month_names)):
if a==month_names[i]:
if int(b)<=day_in_month[i]:
x=True
print("h")
return x
print(is_a_valid_date("february 21"))
Output:
h
True
如果你有年份和月份,你可以使用calendar.monthrange(int year, int month)
來獲取當月的天數
https://docs.python.org/3/library/calendar.html#calendar.monthrange
import calendar
_, days_in_month = calendar.monthrange(2021, 1)
# days_in_month = 31
您應該重構以使用它,因為它也將在沒有額外條件/數據集的情況下正確考慮閏年
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.