python - 如何在while循环或if语句中打印出下一年
问题描述
我目前正在自己做一个在线练习课程。这是我到目前为止的代码。该代码仅正确打印出其中一种条件。if 跳跃条件打印出两个打印语句。我如何让 if 跳跃只打印出一个语句并忽略它之后的内容。
inp_year = int(input("Give year:"))
year = inp_year
leap = year % 4 == 0 and year %100 != 0 or year % 100 == 0 and year % 400 ==0
if leap:
print("The next leap year from",year,"is",year + 4)
while not leap:
year += 1
leap = year % 4 == 0 and year %100 != 0 or year % 100 == 0 and year % 400 ==0
print("The next leap year from",inp_year,"is",year)
解决方案
您可以尝试使用这样的 else 语句:
if leap:
# Code to run when leap is True
print("The next leap year from",year,"is",year + 4)
else:
# Your other code to run when leap is False
while not leap:
year += 1
leap = year % 4 == 0 and year %100 != 0 or year % 100 == 0 and year % 400 ==0
print("The next leap year from",inp_year,"is",year)
如果条件为 True,则该if
语句运行其中缩进的代码。同样,您可以在elif
之后使用语句if
来检查其他条件。最后,如果前面的和条件都不为真,则该else
语句运行其中的代码。if
elif