I'm having problems. Basically the code won't let me add a year after the user submits a year to check if it's a leap year. If it is a leap year, the loop stops, if not I need to add a year and give me the leap year. How can I improve it?
year = int(input("Year:"))
while True:
leapyear = year+1
if leapyear%4 == 0 and leapyear%100 != 0 or leapyear%100 == 0 and leapyear%400 == 0:
break
if True:
print(f"The next leap year after {year} will be {leapyear}")
With leapyear = year+1
you do not increase it, if year=2013
, the loop will make leapyear = 2013+1 = 2014
every time, you need to increase leapyear
year = 2016
leapyear = year
while True:
if leapyear % 4 == 0 and leapyear % 100 != 0 or leapyear % 100 == 0 and leapyear % 400 == 0:
break
leapyear += 1
print(f"The next leap year after {year} will be {leapyear}")
You can shorten while
+ if/break
in one statement
while not (leapyear % 4 == 0 and leapyear % 100 != 0 or leapyear % 100 == 0 and leapyear % 400 == 0):
leapyear += 1
As azro pointed out, leapyear
will only ever equal year + 1
, and to make it increase you could do leapyear = leapyear + 1
.
Also in the code you provided you are checking if the year after the year inputted by the user is a leapyear. If you intended to check the current year as well, you should do the if statement first before increasing leapyear.
if True:
This will always run, so you might as well not include it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.