printing out date in uniform order and a counter - python

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

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)))

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

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"

Related

How to print if the year is leap using if else statements [duplicate]

This question already has answers here:
How to determine whether a year is a leap year?
(13 answers)
Closed 21 days ago.
inp = input("Enter the year: ")
res = "This is not a leap year!"
This code stays the same
print(res)
All leap years are divisible by 4 but not divisible by 100 except if they are divisible by 400. So we can just check if the year is divisible by 4 and not divisible by 100 or divisible by 400 using % operator. Here is the code:
inp = input("Enter the year: ")
if int(inp) % 4 == 0 and int(inp) % 100 != 0 or int(inp) % 400 == 0:
print("This is a leap year!")
else:
print("This is not a leap year!")
Or, if you need to use res you can just do print(res) instead of print("This is not a leap year!")
if int(inp)%400==0:
print("this is a leap year")
elif int(inp)%100=0:
print(res)
elif int(inp)%4==0:
print("this is a leap year")
else:
print(res)

Count the number of leap years between two years and their average using Python

How could you count the number of leap years and calculate their average using the following python script?
start = int(input("Enter start year: "))
end = int(input("Enter end year: "))
if start <= end:
leap_years = [str(x + start) for x in range(end-start) if x % 4 == 0 and x % 100 != 0]
leap_years[-1] += "."
print(f"Here is a list of leap years between {start} and {end}:\n{(', '.join(leap_years))}")
from statistics import mean
leap_years = [start + x for x in range(end-start) if x % 4 == 0 and x % 100 != 0]
avg_leap_year = mean(leap_years)
print(len(leap_years))
print(avg_leap_year)
Please let me know if this script could be improved to be less redundant.
Thank you!
Here is a simple solution:
from statistics import mean
leap_years = [start + x for x in range(end-start) if x % 4 == 0 and x % 100 != 0]
avg_leap_year = mean(leap_years)

Using max() and min() unsuccessfully in Python array

Context: Continuing with my self-learn of Python, I recently completed a textbook exercise that asked for a program that allowed the user to define 'x' number of years and to be able to input, for every month in 'x', a value for rainfall.
Issue: Below is my code, which works 'ok', however the latest exercise demands I 'expand' my code to present the numerically largest and smallest user input rainfall value, in a print statement.
Disclosure: I have looked on S.O to try finding the solution to my question, but nothing seems to be close enough to my challenge, to help me.
What I've tried: I have tried using max() and min() however I keep getting a TypeError: 'int' object is not iterable when I type the code print(max(monthlyRainfall) or print(min(monthlyRainfall)
def yearsToTrack():
userYearsTracking = int(input("How many years do you want to track: "))
return userYearsTracking
def calculationAlgorithm(userYearsTracking):
totalMonths = 0
totalRainfall = 0
for currentYear in range (1, userYearsTracking +1):
for currentMonth in range (1, 13):
monthlyRainfall = int(input("Inches of rainfall for month " + format(currentMonth, "d",) + " | year " +
format(currentYear, "d",)+": "))
totalMonths += 1
totalRainfall += monthlyRainfall
averageRainfall = totalRainfall / totalMonths
print("Total months: " + str(totalMonths))
print("Total rain:", format(totalRainfall), "(inch)")
print("Total average rainfall:", round(averageRainfall,2), "(inch)")
def main():
userYearsTracking = yearsToTrack()
calculationAlgorithm(userYearsTracking)
main()
Is anyone able to offer some 'pointers' as to where I am going wrong?
You can use sys.maxsize and 0 to intilize variables for tracking the minimum and maximum rainfall values that realistically the user will never enter above above or below respectively.
However for the second case just to make sure you can also add a simple check to ensure the user does not enter a negative rainfall amount:
def calculationAlgorithm(userYearsTracking):
totalMonths = 0
totalRainfall = 0
maxRainfall = 0
minRainfall = sys.maxsize
for currentYear in range (1, userYearsTracking +1):
for currentMonth in range (1, 13):
monthlyRainfall = int(input("Inches of rainfall for month " + format(currentMonth, "d",) + " | year " +
format(currentYear, "d",)+": "))
if monthlyRainfall < 0:
print("Error invalid rainfall entered")
sys.exit()
if monthlyRainfall > maxRainfall:
maxRainfall = monthlyRainfall
if monthlyRainfall < minRainfall:
minRainfall = monthlyRainfall
totalMonths += 1
totalRainfall += monthlyRainfall
averageRainfall = totalRainfall / totalMonths
print("Total months: " + str(totalMonths))
print("Total rain:", format(totalRainfall), "(inch)")
print("Total average rainfall:", round(averageRainfall,2), "(inch)")
print("Largest input rainfall: " + str(maxRainfall))
print("Smallest input rainfall: " + str(minRainfall))
Try out the full program with above changes here.
Example Usage:
How many years do you want to track: 1
Inches of rainfall for month 1 | year 1: 2
Inches of rainfall for month 2 | year 1: 2
Inches of rainfall for month 3 | year 1: 2
Inches of rainfall for month 4 | year 1: 2
Inches of rainfall for month 5 | year 1: 4
Inches of rainfall for month 6 | year 1: 1
Inches of rainfall for month 7 | year 1: 2
Inches of rainfall for month 8 | year 1: 2
Inches of rainfall for month 9 | year 1: 2
Inches of rainfall for month 10 | year 1: 2
Inches of rainfall for month 11 | year 1: 2
Inches of rainfall for month 12 | year 1: 2
Total months: 12
Total rain: 25 (inch)
Total average rainfall: 2.08 (inch)
Largest input rainfall: 4
Smallest input rainfall: 1
N.B. I have only used camelCase in naming the new variables as that is the style you are using. I would recommend changing all the names of the variables in your program to snake_case as that is the convention in python.
Python's built-in min() and max() functions expect iterable object like list, set, etc. I think you are putting only one integer which is not so correct (how can you pick min or max number when only 1 number given - obviously it is bot min and max).
One way of doing this would be:
declare list var:
rainfallList = []
Then when you get monthlyRainfall, you should add this code:
rainfallList.append(monthlyRainfall)
After all for loops you can use min(rainfallList) and/or max(rainfallList)
So your final code should be:
def yearsToTrack():
userYearsTracking = int(input("How many years do you want to track: "))
return userYearsTracking
def calculationAlgorithm(userYearsTracking):
totalMonths = 0
totalRainfall = 0
rainfallList = []
for currentYear in range (1, userYearsTracking +1):
for currentMonth in range (1, 13):
monthlyRainfall = int(input("Inches of rainfall for month " + format(currentMonth, "d",) + " | year " +
format(currentYear, "d",)+": "))
totalMonths += 1
rainfallList.append(monthlyRainfall)
totalRainfall += monthlyRainfall
averageRainfall = totalRainfall / totalMonths
print("Total months: " + str(totalMonths))
print("Total rain:", format(totalRainfall), "(inch)")
print("Total average rainfall:", round(averageRainfall,2), "(inch)")
print("Min rain:", format(min(rainfallList)), "(inch)")
print("Max rain:", format(max(rainfallList)), "(inch)")
def main():
userYearsTracking = yearsToTrack()
calculationAlgorithm(userYearsTracking)
main()

TypeError: Can't convert 'int' object to str implicitly/Sorting Array issue

Having an issue with a certain part of the code (I am new to coding and have tried looking through StackOverflow for help):
def totalRainfall (rainfall):
totalRain = 0
month = 0
while month < len(rainfall):
totalRain = rainfall[month] + totalRain
month += 1
return totalRain
TypeError: Can't convert 'int' object to str implicitly
I've tried multiple ways of changing the code to make it a string explicitly as it still giving me various issues.
I'm also having a hard time enhancing the code to sort the array in ascending order and displays the values it contains.
The full code is here:
def main ():
rainfall = rainInput ()
totalRain = totalRainfall (rainfall)
average_Rainfall = averageRainfall (totalRain)
highestMonth, highestMonthly = highestMonthNumber (rainfall)
lowestMonth, lowestMonthly = lowestMonthNumber (rainfall)
print #this is for spacing output
print ('The total rainfall for the year was: ' +str(totalRain) + ' inche(s)')
print #this is for spacing output
print ('The average rainfall for the year was: ' +str(average_Rainfall) +\
' inche(s)')
print #this is for spacing in output
print ('The highest amount of rain was', highestMonthly, 'in' , highestMonth)
print #this is for spacing in output
print ('The lowest amount of rain was', lowestMonthly, 'in' , lowestMonth)
def rainInput ():
rainfall = ['January','Febuary','March','April','May','June','July','August'\
,'September','October','November','December']
month = 0
while month < len(rainfall):
rainfall[month] = input ('Please enter the amount for month ' + str\
(month + 1) + ': ')
month += 1
return rainfall
def totalRainfall (rainfall):
totalRain = 0
month = 0
while month < len(rainfall):
totalRain = rainfall[month] + totalRain
month += 1
return totalRain
def averageRainfall (totalRain):
average_Rainfall = totalRain / 12
return average_Rainfall
def highestMonthNumber (rainfall):
month = ['January','Febuary','March','April','May','June','July','August'\
,'September','October','November','December']
highestMonthly = 0
for m, n in enumerate(rainfall):
if n > highestMonthly:
highestMonthly = n
highestMonth = m
return month[highestMonth], highestMonthly
def lowestMonthNumber (rainfall):
month = ['January','Febuary','March','April','May','June','July','August'\
,'September','October','November','December']
lowestMonthly = 0
for m, n in enumerate(rainfall):
if n < lowestMonthly:
lowestMonthly = n
lowestMonth = m
return month[lowestMonth], lowestMonthly
main()
You have stored strings in your array rainfall, you need to convert them to ints before adding.
def totalRainfall (rainfall):
totalRain = 0
month = 0
while month < len(rainfall):
totalRain = int(rainfall[month]) + totalRain
month += 1
return totalRain
If you want the total rainfall as the sum of the numbers per month, simply use sum() on the list of ints. But as your error suggests, you have a list of strings, which you explicitly have to convert.
Something along the lines of
def totalRainfall (rainfall):
return sum([int(x) for x in rainfall])
The problem with your list being strings will continue to be problematic for you, so as a quick fix, I suggest you change this line
rainfall[month] = input ('Please enter the amount for month ' + str\
(month + 1) + ': ')
to
rainfall[month] = int(input('Please enter the amount for month ' + str\
(month + 1) + ': '))
That way your list contains only numbers and all your other comparisons will work.
You should also add this initialization in your lowestMonthNumber function to avoid UnboundLocalError: local variable 'lowestMonth' referenced before assignment:
lowestMonth = 0
Notice, that by initializing lowestMonthly to 0, you will most likely never get a correct result, since it is highly unlikely that any month has less rainfall.

Regarding summation with a for loop

I'm trying to get the user to input a birth date and then add the individual ints in those numbers. Also, if a sum of any of these digits is greater than or equal to 10, the loop repeats and the process runs again for the value. Here's my code so far
if (sumYear >= 10):
sumYear2=0
for num in str(sumYear):
sumYear2 += int(num)
print(sumYear2)
This works however I think it would be better done as a loop. And if there's some way I won't have to use something like sumYear2 that would be great. Note, I don't think I can use the sum() function.
Thanks guys for the help. I'm having an issue though. I'm not sure why this code isn't being evaluated when I provide the month as 02 and the day as 30
while True:
year=input("Please enter the year you were born: ")
month=input("Please enter the month you were born: ")
day=input("Please enter the day you were born: ")
if(int(month)==2 and int(day)<=29):
break
elif(int(month)==1 or 3 or 5 or 7 or 8 or 10 or 12 and int(day)<=31 ):
break
elif(int(month)==4 or 6 or 9 or 11 and int(day)<=30):
break
else:
print("Please enter a valid input")
Too much work.
singledigitsum = (int(inputvalue) - 1) % 9 + 1
Note that this will fail for numbers less than 1.
#Ignacio Vazquez-Abrams's answer provides the formula. But if there were none then your code as a loop without using sumYear2 could look like:
while sumYear >= 10:
sumYear = sum(map(int, str(sumYear)))
If you're not allowed to use sum (a homework) then:
while sumYear >= 10:
s = 0
for d in str(sumYear):
s += int(d)
sumYear = s
For the second question assuming Python 3:
while True:
try:
year = int(input("Please enter the year you were born: "))
month = int(input("Please enter the month you were born: "))
day = int(input("Please enter the day you were born: "))
birthday = datetime.date(year, month, day)
except ValueError as e:
print("error: %s" % (e,))
else:
break
If you are not allowed to use try/except then:
year = get_int("Please enter the year you were born: ",
datetime.MINYEAR, datetime.MAXYEAR)
month = get_int("Please enter the month you were born: ",
1, 12)
day = get_int("Please enter the day you were born: ",
1, number_of_days_in_month(year, month))
birthday = datetime.date(year, month, day)
Where get_int():
def get_int(prompt, minvalue, maxvalue):
"""Get an integer from user."""
while True:
s = input(prompt)
if s.strip().isdigit():
v = int(s)
if minvalue <= v <= maxvalue:
return v
print("error: the input is not an integer in range [%d, %d]" % (
minvalue, maxvalue))
And number_of_days_in_month():
# number of days in a month disregarding leap years
ndays = [0]*13
ndays[1::2] = [31]*len(ndays[1::2]) # odd months
ndays[::2] = [30]*len(ndays[::2]) # even months
ndays[2] = 28 # February
ndays[8] = 31 # August
# fill other months here ...
def number_of_days_in_month(year, month):
return ndays[month] + (month == 2 and isleap(year))
You can do this
>>> d=123456
>>> sum(int(c) for c in str(d))
21

Categories