酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

Python:编写 ndays 函数精准返回指定年月天数及测试代码

```python def ndays(y, m): # 判断是否是闰年 if (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0): leap_year = True else: leap_year = False # 根据月份返回天数 if m in (1, 3, 5, 7, 8, 10, 12): return 31 elif m in (4, 6, 9, 11): return 30 elif m == 2: if leap_year: return 29 else: return 28 else: return 0 # 非法月份,返回0 def main(): while True: try: year = int(input("请输入年份(>=1),否则为1:")) month = int(input("请输入月份(1~12),否则<1为1、>12为12:")) if year < 1: year = 1 if month < 1: month = 1 elif month > 12: month = 12 days = ndays(year, month) print(days) except ValueError: print("输入错误,请输入整数。") except Exception as e: print(f"发生错误:{e}") if __name__ == "__main__": main() ``` ######[AI写代码神器 | 375点数解答 | 2024-11-30 15:06:46]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]