笨鸟编程-零基础入门Pyhton教程

 找回密码
 立即注册
查看: 3591|回复: 0

用于检查闰年的 Python 程序

[复制链接]

新手上路

Rank: 1

积分
13
发表于 2022-3-9 16:32:17 | 显示全部楼层 |阅读模式
介绍
有时很难判断一年是否是闰年,特别是1900-1999年的年份!
你有没有想过如何使用Python检查一年是否是闰年?
在我们掌握编码之前,请查看本文以获取有关Python的更多基本信息。
让我们潜入编码
我们将创建一个程序来检查闰年
有两种方法:
  • 使用日历模块。
  • 使用运算符。
1. 使用压延机模块
因为这是最简单的,因为只需要导入日历并使用如下所示:
  1. <p style="margin: 0 0 var(--content-rhythm) 0; box-sizing: border-box;"><span style="background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; border-radius: var(--radius); max-width: 100%; padding: 0.1em 0.25em; box-sizing: border-box;">calender.isleap()</span>
  2. </p><div class="highlight js-code-highlight" style="box-sizing: border-box; background-image: ; background-position-x: ; background-position-y: ; background-size: ; background-repeat-x: ; background-repeat-y: ; background-attachment: ; background-origin: ; background-clip: ; border-radius: var(--radius); margin: 0 0 var(--content-rhythm) 0; overflow-x: auto; overflow-wrap: initial; padding: var(--su-6); position: relative;"><pre class="highlight plaintext" style="box-sizing: border-box; background-image: ; background-position-x: ; background-position-y: ; background-size: ; background-repeat-x: ; background-repeat-y: ; background-attachment: ; background-origin: ; background-clip: ; overflow: auto;"><span style="background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial; border-radius: var(--radius); max-width: 100%; box-sizing: border-box;">import calendar

  3. year = int(input("Enter the year : "))

  4. print(calendar.isleap(year))</span></pre></div>
复制代码




如果年份分别是闰年,则输入的年份将转换为 True 或 False。
2. 使用运算符
这种方法,我们必须定义我们的程序,如何检查一年是否是一个飞跃。
首先,我们必须从用户那里获得年份。除以100,这意味着世纪年,除以400。
如果不除以100意味着不是一个世纪年,而是除以4的年份是闰年。
闰年正好可以被4整除,除了世纪年(以00结尾的年份)。世纪年只有在完全可以被400整除时才是闰年。
如下所示:
一些输出:
  1. Enter a year : 2030
  2. 2030 is not a leap year

  3. Enter a year : 2000
  4. 2000 is a leap year

  5. Enter a year : 1900
  6. 1900 is not a leap year

  7. Enter a year : 1904
  8. 1904 is a leap year
复制代码




现在您知道如何使用两种方式检查一年是否是闰年

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|笨鸟自学网 ( 粤ICP备20019910号 )

GMT+8, 2024-9-8 11:15 , Processed in 0.019658 second(s), 19 queries .

© 2001-2020

快速回复 返回顶部 返回列表