user2947950
user2947950

Reputation: 129

printing out date in uniform order and a counter

I have been doing these for hours! please help! New to python

example 1990 for input year and 2000 for end year.

basically i want the output to be

the years are 1992 1996 2000

there are 3 counts

I thought of converting them to a list and using len() but i do not know how

#inputs
year = int(raw_input("Input year: "))
endyear = int(raw_input("Input end year:"))

print "The number of leap years are "

counter = 0
for x in range(year,endyear+1):
    
    if x % 4 == 0 and (x % 100 != 0 or x % 400 == 0):
        counter +=1
        print x
        print counter

heres the current result :(

The number of leap years are

1900
0
1901
0
1902
0
1903
0

Upvotes: 0

Views: 57

Answers (3)

vishes_shell
vishes_shell

Reputation: 23484

The problem was when needed year occur, the break stopped your loop.

year = int(raw_input("Input year: "))
end_year = int(raw_input("Input end year:"))

print "The number of leap years are "

counter = 0
temp = []
for x in range(year, end_year+1):
    if x % 4 == 0 and (x % 100 != 0 or x % 400 == 0):
           counter +=1
           temp.append(x)
print('the years are {}'.format(temp))
print('there are {} counts'.format(counter))

You also might want to remove brackets in "the years are []", you can do that with

print('the years are ', ' '.join(map(str, temp)))

Upvotes: 1

GpG
GpG

Reputation: 512

you can do it in a shorter way:

from calendar import isleap
years = [ str(x) for x in range(year,endyear+1) if isleap(x)]

print "the years are ", ''.join(elem + " " for elem in years)
print "there are ", len(years), "counts"

Upvotes: 0

Daniel
Daniel

Reputation: 5381

You can use the calendar.isleap to count the number of leap years between given years.

from calendar import isleap
year = int(raw_input("Input year: "))
endyear = int(raw_input("Input end year:"))
print "The number of leap years are "
counter = 0
years = []
for x in range(year,endyear+1):
    if isleap(x):
        counter +=1
        print x
        print counter

Upvotes: 1

Related Questions