问题描述
我目前正在独自完成在线实践课程。这是我到目前为止的代码。该代码仅正确打印出其中一种条件。 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,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,year)
如果条件为True,则if
语句将在其中运行缩进的代码。同样,您可以在elif
之后使用if
语句来检查其他条件。最后,如果先前的else
和if
条件都不为True,则elif
语句将在其中运行代码。