打印给定月份和年份中的天数 [Python]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18325705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:29:24  来源:igfitidea点击:

Printing the number of days in a given month and year [Python]

pythonpython-2.7calendardays

提问by James Adams

I've been trying to work out a way to accomplish what's in the title, without using any imported calendar/datetime libs from Python. There's little function at the top for checking whether or not the year is a leap year, which I want to be able to reference when printing the number of days in a given February, however I'm not too sure how to do so. (I've guessed with something like output. bla bla)

我一直在尝试找出一种方法来完成标题中的内容,而不使用任何从 Python 导入的日历/日期时间库。顶部几乎没有用于检查年份是否为闰年的功能,我希望在打印给定 2 月的天数时能够参考它,但是我不太确定该怎么做。(我已经猜到了类似输出的东西。bla bla)

So far I've come up with something like this, which should make clear what I want to do, but I'm still a bit new to Python, so I would love a few tips/help on fixing up my code for the task.

到目前为止,我已经想出了这样的东西,它应该清楚我想要做什么,但我对 Python 还是有点陌生​​,所以我希望能得到一些关于修复任务代码的提示/帮助.

# A function to determine if a year is a leap year.
# Do not change this function.
def is_leap_year (year):
    return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)

# You should complete the definition of this function:

 def days_in_month(month, year):

    if month == 'September' or month == 'April' or month == 'June' or month == 'November'
    print 30

    elseif month == 'January' or month == 'March' or month == 'May' or month== 'July' or month == 'August' or month == 'October'\
    or month== 'December'
     print 31

    elseif month == 'February' and output.is_leap_year = True
    print 29

    elseif month == 'February' and output.is_leap_year = False
    print 28

    else print 'Blank'

Ok I've fixed up my code, and it seems to output the correct data for every month but February:

好的,我已经修复了我的代码,它似乎每个月都输出正确的数据,但 2 月:

# A function to determine if a year is a leap year.
# Do not change this function.
def is_leap_year (year):
    return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)

# You should complete the definition of this function:

def days_in_month(month, year):

    if month in ['September', 'April', 'June', 'November']:
        print 30

    elif month in ['January', 'March', 'May', 'July', 'August','October','December']:
        print 31        

    elif month == 'February' and is_leap_year == True:
        print 29

    elif month == 'February' and is_leap_year == False:
        print 28

Any hints to fix up outputting for February?

有什么提示可以修复 2 月的输出吗?

EDIT: Just needed to add the argument year when referencing the first function. Here is the 100% working code for future reference:

编辑:只需要在引用第一个函数时添加参数年份。这是 100% 工作代码以供将来参考:

# A function to determine if a year is a leap year.
# Do not change this function.
def is_leap_year(year):
    return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)

# You should complete the definition of this function:

def days_in_month(month, year):

    if month in ['September', 'April', 'June', 'November']:
        print 30

    elif month in ['January', 'March', 'May', 'July', 'August','October','December']:
        print 31        

    elif month == 'February' and is_leap_year(year) == True:
        print 29

    elif month == 'February' and is_leap_year(year) == False:
        print 28

    else:
        return None

?

?

?

?

?

?

采纳答案by David.Zheng

Some syntax error in your code:

您的代码中存在一些语法错误:

  1. There should be no space before def days_in_month(month,year). Python use indentation to separate code blocks. This is the error you given in comment.
  2. There is no elseifin python, it should be elif
  3. output.is_leap_year = True, it should be is_leap_year(year) == True. The Falsepart should be changed too.
  4. after ifstatement and elsethere should be a :, like

    if month == 'September' or month == 'April' or month == 'June' or month == 'November':
        print 30
    elif month == 'January' or month == 'March' or month == 'May' or month== 'July' or month == 'August' or month == 'October' or month== 'December':
        print 31
    elif month == 'February' and is_leap_year(year) == True:
        print 29
    elif month == 'February' and is_leap_year(year) == False:
        print 28
    else:
        print 'Blank'
    
  1. 之前应该没有空格def days_in_month(month,year)。Python 使用缩进来分隔代码块。这是您在评论中给出的错误。
  2. elseifpython中没有,应该是elif
  3. output.is_leap_year = True,应该是is_leap_year(year) == True。该False部分也应该被改变。
  4. if声明之后,else应该有一个:,比如

    if month == 'September' or month == 'April' or month == 'June' or month == 'November':
        print 30
    elif month == 'January' or month == 'March' or month == 'May' or month== 'July' or month == 'August' or month == 'October' or month== 'December':
        print 31
    elif month == 'February' and is_leap_year(year) == True:
        print 29
    elif month == 'February' and is_leap_year(year) == False:
        print 28
    else:
        print 'Blank'
    

回答by Madison May

A more pythonic approach would be to define the mapping in a dictionary, then simply retrieve the values from the dictionary.

更pythonic 的方法是在字典中定义映射,然后简单地从字典中检索值。

Try it out:

试试看:

days_in_month_dict = {"January": 31, "February": 28, 
                      "March": 31, "April": 30,
                      "May": 31, "June": 30, 
                      "July": 31, "August": 31,
                      "September": 30, "October": 31,
                      "November": 30, "December": 31}

def is_leap_year(year):
    return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)

def days_in_month(year, month):
    if is_leap_year(year) and month == "February":
        return 28

    try: 
        #attempt to get value from dictionary 
        return days_in_month_dict[month]
    except KeyError:
        #key does not exist, so we caught the error
        return None

回答by punit tiwari

"""
Takes the year and month as input and returns the no. of days
"""
def is_leap_year (year):
    return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)

def days_in_month(month, year):
    if month == 'September' or month == 'April' or month == 'June' or month == 'November':
        result=30
    elif month == 'January' or month == 'March' or month == 'May' or month== 'July' or month == 'August' or month == 'October'or month== 'December':
        result=31

    elif month == 'February' and output.is_leap_year ==True:
        result=29

    elif month == 'February' and output.is_leap_year == False:
        result=28
    return result

print(is_leap_year(2016))
print(days_in_month('September',2016))

回答by Raunaq

month = int (input ('month (1-12): '))

if month < 13:
    if month == 2:
        year = int (input ('year: '))
        if year % 4 == 0:
            if year % 100 == 0:
                if year % 400 == 0:
                    print ('29')
                else:
                    print ('28')
            else:
                print ('29')
        else:
            print ('28')

    elif month >= 8:
        if month % 2 == 0:
            print ('31')
        else:
            print ('30')

    elif month % 2 == 0:
        print ('30')
    else:
        print ('31')

else:
    print ('Only 1-12 accepted')