I write a code which is to find the remaining day and passed days in a year. I have to use for loop for my homework. This code can be true sometimes but such as day:29 month:12 year:2020 dates
program find wrong left days and passed days. Where is the mistake on my code ı couldn’t understand.
day = int(input("Enter a day: "))
month = int(input("Enter a month: "))
year = int(input("Enter a year: "))
month_day = None
days_passed = 0
days_left = None
if year % 4 == 0 and year > 0:
if year % 100 != 0:
year = "Leap year"
elif year % 100 == 0:
if year % 400 == 0:
year = "Leap year"
else:
year = "Not leap year"
elif year <= 0:
print("Please enter a valid number")
elif year % 4 != 0 and year > 0:
year = "Not leap year"
elif month < 1 and month > 12:
print("Please enter a valid number")
if year == "Leap year":
if month == 2:
month_day = 29
elif month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
month_day = 31
else:
month_day = 30
elif year == "Not leap year":
if month == 2:
month_day = 28
elif month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
month_day = 31
else:
month_day = 30
if year == "Leap year":
for i in range(1,month):
days_passed += month_day
month -= 1
if month == 0:
break
days_passed += day
days_left = 366- days_passed
print("Days passed: ", days_passed)
print("Days left: ",days_left)
if year == "Not leap year":
for i in range(1, month):
days_passed += month_day
month -= 1
if month == 1:
break
days_passed += day
days_left = 365 - days_passed
print("Days passed: ", days_passed )
print("Days left: ", days_left)
>Solution :
Without the aid of standard modules, for loops or dictionaries, you could do it like this:
def isleap(y):
if y % 400 == 0:
return True
if y % 100 == 0:
return False
return y % 4 == 0
def elapsed(d, m, y):
assert y > 0
assert m > 0 and m < 13
assert d > 0
dim = [0, 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
dim[2] = 29 if isleap(y) else 28
assert d <= dim[m]
return sum(dim[0:m]) + d
print(elapsed(1, 3, 1980))