在 python 函數中檢查月份的有效性時出錯 (Error in checking validity of month in python function)


問題描述

在 python 函數中檢查月份的有效性時出錯 (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: not enough values to unpack(expected 2,got 1)
嘗試檢查輸入中的給定字符串是否是月份名稱中提到的有效月份 如果與day_in_month中的天數相比,它後面的日期也是有效的


參考解法

方法 1:

You should avoid using global and you not use your parameter date at all!

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

If you want to catch the edge cases like upper case and worng input:

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

方法 2:

Try this:



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

方法 3:

If you have the year and month, you can use calendar.monthrange(int year, int month) to get the number of days in the month

https://docs.python.org/3/library/calendar.html#calendar.monthrange

import calendar
_, days_in_month = calendar.monthrange(2021, 1)
# days_in_month = 31

You should refactor to use this as it will also factor in leap year correctly without extra conditions/data‑sets

(by Harsh Rajvanshijacob galamtop talentJohn)

參考文件

  1. Error in checking validity of month in python function (CC BY‑SA 2.5/3.0/4.0)

#split #Python #list






相關問題

將 xml 元素內容拆分為固定行數 (Split xml element content into fix number of lines)

是否有任何標准說明“aba”.split(/a/) 是否應該返回 1,2 或 3 個元素? (Is there any standard which says if "aba".split(/a/) should return 1,2, or 3 elements?)

Cố gắng gọi các phương thức trong phương thức main với biến được khởi tạo trong các phương thức khác (Trying to call methods in main method with variable initialized in other methods)

使用 Java-Regex 與 Regex 成對拆分多行文本 (Split text with Java-Regex in pairs with Regex over several lines)

如何分割字節數組 (How to split a byte array)

String componentsSeparatedByString 做一次 (String componentsSeparatedByString do one time)

從一行文本中獲取特定數據 (Get specific data from a line of text)

(Python)拆分字符串多個分隔符更有效?1) 使用多重替換方法然後使用拆分 2) 使用正則表達式 ((Python) which is more efficient to split a string multiple separators? 1) Using multiple replace method then using split 2) using regular Expressions)

ValueError:發現樣本數量不一致的輸入變量:[2935848、2935849] (ValueError: Found input variables with inconsistent numbers of samples: [2935848, 2935849])

在 Powershell 中拆分和添加字符串 (Splitting and Adding String in Powershell)

在 python 函數中檢查月份的有效性時出錯 (Error in checking validity of month in python function)

如何將 .obj 文件拆分為其他兩個文件(python、open3d)? (How to split a .obj file into two other files (python, open3d)?)







留言討論