Slow Poke Slow Poke - 2 months ago 17
Python Question

Having output issues with python; loop totals and averages

Having a few output issues with my nested loop, normally I use

break
to add some lines into my code or
print()


When I use
print()
within my code my output looks like I am typing totals on a new line all together that is not what I want

Following is a picture of my current output and where I need a blank line;

enter image description here

Second thing:

My code is not calculating the information correctly to find the total and average rainfall per month.

code follows

def main():

#define accumulators
monthRain = 0
year = 0
monthTotal = 0
months = 0
total = 0

#get # of years
year = int(input("Enter the number of years to collect data for: "))

#blank line
print()

#define month total befor it is changed below with year + 1
monthTotal = year * 12

#define how many months per year
months = 12

#Find average rainfall per month
for year in range(year):
#accumulator for rain per month
total = 0
#get rainfall per month
print('Next you will enter 12 months of rainfall data for year', year + 1)
for month in range(months):
print("Enter the rainfall for month", month + 1, end='')
monthRain = float(input(': '))

#add monthly raingfall to accumulator
total += monthRain
average = total / monthTotal

#total months of data
print('You have entered data for', monthTotal,'months')

#blank line
print()

#total rainfall
print('The total rainfall for the collected months is:', total)
print('The average monthly rainfall for the collected months is:', average)


main()

Answer

Following is a picture of my current output and where I need a blank line

In order to get a blank line before You have entered data for, add \n at the start of the string. It represents new line. Hence your print statement should be as:

print("\nYou have entered data for")

my code is not calculating the information correctly to find the total and average rainfall per month.

On dividing two int values, python returns int as by default excluding the float precision. In order to get the float value, conver either of numerator or denomenator to float. Example:

>>> 1/5
0  # <-- Ignored float value as between two int
>>> 1/float(5)
0.2  #<-- Float value to conversion of denomenator to float

Also, in average = total / monthTotal, I believe that the average is need for per month basis. It should be month instead of monthTotal. Because total will be having the sum of rain for month months. In order to get average of rain in month months, your equation should be:

average = total / float(month)