一种检查月份和日期组合在Python 3中是否有效的方法

时间:2018-09-14 01:22:03

标签: python

  1. 您好,我目前正在学习基本的python类,并且目前正在学习if-else语句。我理解if-else语句的概念,但是目前有一件事困扰着我。我需要创建一个提示,允许用户输入1到12的月份,从1-31的天,并且提示将通过确定输入是否在这些范围内来判断输入是否有效。但是,从逻辑上讲,某些日期是没有意义的。例如,您不能有4/31或6/31,因为那几个月只有30天。我目前正在尝试编写一个代码,该代码将告诉用户月/日组合是否有效/无效,但我不知道该如何做。我很想被教怎么做。

这是我到目前为止所拥有的:

month = int(input("Please enter a month in numeric form from 1-12: "))
if month == 1 or 3 or 5 or 7 or 8 or 10 or 12:
    print("Valid Month with more than 30 days")
elif month == 4 or 6 or 9 or 11:
    print("Valid Month with 30 days")
elif month == 2:
    print("Month has only 28 days max")
else:
    print("Invalid Month")
day = int(input("Please enter a day in numeric form from 1-31: "))
if day == 0 < day < 32:
    print("Valid Day")
else:
    print("Invalid Day")

5 个答案:

答案 0 :(得分:1)

这不是or的工作方式。您可能想将in与一组类似的

一起使用
if month in {1, 3, 5, 7, 8, 10, 12}:

or是一个二进制运算符,如果为true,则返回其左参数,否则返回其右参数,因此

foo or bar就像说foo if foo else bar

答案 1 :(得分:1)

使用列表或字典

...
days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if 0 < day <= days[month]:
    print("Valid Day")
else:
    print("Invalid Day")

答案 2 :(得分:0)

您可以切片:

list(range(1,13))[1::2][1:]

并且:

list(range(1,13))[::2]

另一方面,用于月份检查:

0 < day < 32

演示:

month = int(input("Please enter a month in numeric form from 1-12: "))
if month in list(range(1,13))[::2]:
    print("Valid Month with more than 30 days")
elif month in list(range(1,13))[1::2][1:]:
    print("Valid Month with 30 days")
elif month == 2:
    print("Month has only 29 days max")
else:
    print("Invalid Month")
day = int(input("Please enter a day in numeric form from 1-31: "))
if 0 < day < 32:
    print("Valid Day")
else:
    print("Invalid Day")

示例输出:

Please enter a month in numeric form from 1-12: 3
Valid Month with more than 30 days
Please enter a day in numeric form from 1-31: 3
Valid Day

Please enter a month in numeric form from 1-12: 4
Valid Month with 30 days
Please enter a day in numeric form from 1-31: 244
Invalid Day

Please enter a month in numeric form from 1-12: 354
Invalid Month
Please enter a day in numeric form from 1-31: 3
Valid Day

可以做leap年和其他有趣的事情:

import calendar
month = int(input("Please enter a month in numeric form from 1-12: "))
if month in list(range(1,13))[::2]:
    print("Valid Month with more than 30 days")
    num=31
elif month in list(range(1,13))[1::2][1:]:
    print("Valid Month with 30 days")
    num=30
elif month == 2:
    year=int(input("Since it's february, what year is it:"))
    if calendar.isleap(year):
       print("Month has only 29 days")
       num=29
    else:
       print("Month has only 28 days")
       num=28
else:
    print("Invalid Month")
day = int(input("Please enter a day in numeric form from 1-31: "))
if 0 < day < num:
    print("Valid Day")
else:
    print("Invalid Day")

答案 3 :(得分:0)

在学校上学python之前,我已经做过类似的事情。

无论如何,从逻辑上讲,这不是您的使用方式,或者,以人类语言肯定是有意义的,但是python不够“聪明”,无法弄清楚。我会帮您解决这个问题,您需要在每个或之后使用“输入”或添加“月”一词。

提示:将来在代码中添加注释以帮助我们,请使用“#”告诉我们每个位的作用,这对于更复杂的程序很有用。

def main():
month = int(input("Please enter a month in numeric form from 1-12: "))
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
    print("Valid Month with more than 30 days")

elif month == 4 or month == 6 or month == 9 or month == 11:
    print("Valid Month with 30 days")
elif month == 2:
    print("Month has only 28 days max")
else:
    print("Invalid Month")

day = int(input("Please enter a day in numeric form from 1-31: ")) #storing variables

if month == 4 and day <= 30: #if you haven't learned "and" yet, use your own way
    print("Valid Day")
elif month == 6 and day <= 30:
    print("Valid Day")
elif month == 9 and day <= 30:
    print("Valid Day")
elif month == 11 and day <= 30:
    print("Valid Day")
elif month == 2 and day <= 28: #February case
    print("Valid Day")
else:
    print("That combination is not a valid day!")

main()

输出: 请以1-12的数字形式输入月份:2 一个月最多只有28天 请以1-31的数字形式输入日期:28 有效日期

请以1到12的数字形式输入月份:4 有效期为30天 请以1-31的数字形式输入日期:31 这种组合不是有效的一天!

希望这会有所帮助!

答案 4 :(得分:0)

下面的parse_month_day函数将采用类似“ 07-28”的字符串,并返回一个元组(7, 28)。有单元测试可以说明其用法。

import unittest


def parse_month_day(month_day_str):
    """Returns month, day tuple from a MM-DD string.

    Args:
        month_day_str (str):

    Returns:
        tuple(int, int): Tuple of month and day.

    """
    try:
        month, day = (int(part) for part in month_day_str.split("-"))
    except ValueError:
        raise ValueError("Invalid month day string, expected MM-DD or M-D format.")

    if not 1 <= month <= 12:
        raise ValueError(f"Invalid month {month:02}, expected to be 01-12")

    valid_month_days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    day_bound = valid_month_days[month - 1]

    if not 1 <= day <= day_bound:
        raise ValueError(
            f"Invalid day {day:02} for month {month:02}, expected to be 01-{day_bound}"
        )

    return month, day


class TestParseMonthDay(unittest.TestCase):
    def test_parse_month_day_string(self):
        actual = parse_month_day("07-28")
        expected = (7, 28)
        self.assertEqual(actual, expected)

    def test_invalid_month_day_string(self):
        with self.assertRaisesRegex(ValueError, "Invalid month day string, expected MM-DD or M-D format"):
            parse_month_day("Jul-28")

    def test_invalid_month_value(self):
        with self.assertRaisesRegex(ValueError, "Invalid month 00, expected to be 01-12"):
            parse_month_day("0-28")

    def test_invalid_day_value(self):
        with self.assertRaisesRegex(ValueError, "Invalid day 32 for month 07, expected to be 01-31"):
            parse_month_day("07-32")

        with self.assertRaisesRegex(ValueError, "Invalid day 30 for month 02, expected to be 01-29"):
            parse_month_day("02-30")

if __name__ == "__main__":
    unittest.main()