leap_year = int(input('Year: '))
initial_year = leap_year
while True:
leap_year += 1
if leap_year % 4 == 0 and (leap_year % 100 == 0 and leap_year % 400) == 0:
print(f'The next leap year after {initial_year} is {leap_year}')
break有人能解释一下这是怎么回事吗?
if leap_year % 4 == 0 and (leap_year % 100 == 0 and leap_year % 400) == 0: 与此不同:
if leap_year % 4 == 0 and leap_year % 100 == 0 and leap_year % 400 == 0:发布于 2022-09-18 23:35:41
令人困惑的是,在最后怎么会有一个== 0,这在功能上与将not放在该部分之前一样。与其他模块操作不同的是,leap_year % 400与任何东西都没有直接比较,这也让人困惑。
更清楚的是重写它:
leap_year % 4 == 0 and not (leap_year % 100 == 0 and leap_year % 400 != 0)如果我们应用德摩根定律,可能会更清楚:
leap_year % 4 == 0 and (leap_year % 100 != 0 or leap_year % 400 == 0)最后,您可以在这里删除括号,但是保持它们的可读性更好。
现在应该很明显,它与您提到的其他条件有什么不同。
*实际发生的情况是,and计算leap_year % 100 == 0,如果它是假的,则会得到结果,即False__;如果它是真实的,则会得到leap_year % 400__的结果,即range(0, 400, 100)__中的int。这与最后的== 0进行了比较,而对于False来说,这是因为False == 0__。
https://stackoverflow.com/questions/73766977
复制相似问题