I am trying to write a program that uses nested loops to collect data and calculate the average rainfall over a period of years. The program should ask the number of years. The outer loop will iterate once for each year. The inner loop will iterate twelve times, once for each month. Each iteration of the inner loop will ask the user for the number of inches of rainfall for that month.
After all iterations, the program should display the nubmer of months, the total inches of rainfall and the average rainfall per month for the entire period.
years = int(input('How many years do you want to track? '))
months = 12
for years_rain in range(years):
total= 0.0
print('\nYear number', years_rain + 1)
print('------------------------------')
for month in range(months):
print('How many inches for month ', month + 1, end='')
rain = int(input(' did it rain? '))
total += rain
number_months = years * months
average = total / number_months
print('The total inches of rain was ', format(total, '.2f'),'.')
print('The number of months measured was', number_months)
print('The average rainfall was', format(average, '.2f'), 'inches')
The logic for this program is off. It is basing the average rainfall off the last year's total rainfall, not all of the years' rainfall totals.
Where am I going wrong in the logic of this program?
With properly formatted code, you'll notice that you do:
for years_rain in range(years):
total= 0.0
print('\nYear number', years_rain + 1)
...
Which resets the total to zero each iteration of your year loop. Change it instead to:
total = 0.0
for years_rain in range(years):
print('\nYear number', years_rain + 1)
...
Your total value is being reset so you need a way to keep track of the grandTotal. Here's one way to do this:
years = int(input('How many years do you want to track? '))
months = 12
grandTotal = 0.0 // will store TOTAL rainfall
for years_rain in range(years):
total= 0.0
print('\nYear number', years_rain + 1)
print('------------------------------')
for month in range(months):
print('How many inches for month ', month + 1, end='')
rain = int(input(' did it rain? '))
total += rain
grandTotal += total // add total to the grandTotal
number_months = years * months
average = grandTotal / number_months
print('The total inches of rain was ', format(average, '.2f'),'.')
print('The number of months measured was', number_months)
print('The average rainfall was', format(average, '.2f'), 'inches')
Related
Help me!! It's not justified (python)
# Accept the inputs
startBalance = float(input("Enter the investment amount: "))
years = int(input("Enter the number of years: "))
rate = int(input("Enter the rate as a %: "))
# Convert the rate to a decimal number
rate = rate / 100
# Initialize the accumulator for the interest
totalInterest = 0.0
# Display the header for the table V.3
print("%4s%18s%10s%16s" % \
("Year", "Starting balance",
"Interest", "Ending balance"))
# f string
# Compute and display the results for each year
for year in range(1, years + 1):
interest = startBalance * rate
endBalance = startBalance + interest
print(f"{year:>4}{startBalance:<18.2f}{interest:>10.2f}{endBalance:>16.2f}")
startBalance = endBalance
totalInterest += interest
# Display the totals for the period
print("Ending balance: $%0.2f" % endBalance)
print("Total interest earned: $%0.2f" % totalInterest)
I was trying to align data in a table on the right side of the column. I use f string and formatting type in the variable placeholder but there was no alignment.
I try to run the code on jupyter and VS Code.
There is no need to mix different template systems. Just use f-strings:
pv = float(input('Enter the investment amount: '))
years = range(int(input('Enter the number of years: ')))
rate = int(input('Enter the rate as a %: ')) / 100
interests = 0.0
print('Year Starting balance Interest Ending balance')
for year in years:
interest = pv * rate
fv = pv + interest
print(f'{year + 1:>4d}{pv:>17.2f}{interest:>10.2f}{fv:>16.2f}')
pv = fv
interests += interest
print(f'Ending balance: ${fv:0.2f}')
print(f'Total interest earned: ${interests:0.2f}')
And here is an example of the output:
Enter the investment amount: 200
Enter the number of years: 10
Enter the rate as a %: 15
Year Starting balance Interest Ending balance
1 200.00 30.00 230.00
2 230.00 34.50 264.50
3 264.50 39.67 304.18
4 304.18 45.63 349.80
5 349.80 52.47 402.27
6 402.27 60.34 462.61
7 462.61 69.39 532.00
8 532.00 79.80 611.80
9 611.80 91.77 703.58
10 703.58 105.54 809.11
Ending balance: $809.11
Total interest earned: $609.11
I am trying to make a sales calculator that shows different things such as what was the maximum sale for the week and which day was it, what was the minimum sale for the week and which day was it, what is the total amount of sales of all days added together, average sales for the week, and a sales commission of 0$ for less than 100$ made, 25$ for sales between $100 and 250$, 30$ for sales between $250 and $500, and 40$ for sales over 500$.
I've tried different ways of calculating the average but can't get it to work and i'm not sure how to work in the sales commission as well as linking the min and max to the day of the week they occur on.
This is what I currently:
print ("Sales Calculator Program")
print ('\n')
expenses = []
for day_number in range (1, 5 + 1):
while True:
user_input = float(input(f"Enter sales for day {day_number}\n> "))
if user_input >= 0:
expenses.append(user_input)
break
else:
print(f"Amount may not be negative. Try again:")
print ('\n')
average = average(expenses)
finalExpenses = sum(expenses)
print ("Total weekly sales were $" +str(finalExpenses))
print ("Average of the sales is $" +str(average))
This is what i'm trying to get it to look like:
Enter sales for day 1: 10.22 (User input)
Enter sales for day 2: 4.12 (User input)
Enter sales for day 3: 3.78 (User input)
Enter sales for day 4: 6.82 (User input)
Enter sales for day 5: 22.45 (User input)
Maximum sales was on Friday which is $22.45
Minimum sales was on Wednesday which is $3.78
Total weekly sales were $47.39
Average of the sales is $9.48
Sales too low for commission must earn more than $100
Thank you!
print ("Sales Calculator Program")
print ('\n')
expenses = []
for day_number in range (1, 5 + 1):
while True:
user_input = float(input(f"Enter sales for day {day_number}\n> "))
if user_input >= 0:
expenses.append((day_number,user_input))
break
else:
print(f"Amount may not be negative. Try again:")
print ('\n')
max = max(expenses, key=lambda x: x[1])
min = min(expenses, key=lambda x: x[1])
total = sum(map(lambda x: int(x[1]), expenses))
average = total/len(expenses)
for item in expenses :
if item[0] == 1:
Monday ...
For the rest you should try urself now you can use max min sum etc ... try to know more about some builtin functions before you ask here :))
You can do it like this.
print ("Sales Calculator Program")
print ('\n')
expenses = []
for day in range(1, 6):
while True:
sales = float(input(f"Enter sales for day {day}\n> "))
if sales >= 0:
expenses.append((sales, day))
break
else:
print(f"Amount may not be negative. Try again:")
print ('\n')
days = ['', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
maxval = max(expenses, key=lambda x: x[0]) # could also use operator.itemgetter
minval = min(expenses, key=lambda x: x[0])
total = sum(e[0] for e in expenses)
average = total / len(expenses)
print('Maximum sales was on %s which is $%.2f' % (days[maxval[1]], maxval[0]))
print('Minimum sales was on %s which is $%.2f' % (days[minval[1]], minval[0]))
print ("Total weekly sales were $%.2f" % total)
print ("Average of the sales is $%.2f" % (average))
if total < 100.0:
print('Sales too low for commission must earn more than $100')
Store the daily value with the day index in a tuple. You can then use max or min with a key function to pick out element 0 as the one to use in the calculation of max/min. When you come to print it the second element in the tuple can be used to index into the days array to get the day name.
The calculation of the mean average should be pretty self explanatory.
Note that floating point numbers are not suitable for storing monetary values in any application that needs to be correct. Instead store values in cent/pence or use decimal.
I am a new to python as a whole coming from COBOL.
I am trying to create a program to take user input about a loan, and then output a schedule of payments and how they will affect the balance of the loan.
#ACCEPTS USER INPUT AND ASSIGNS VALUES
print('lets try to amortize a loan')
input()
print('when will this loan begin?')
year = int(input('year: '))
month = int(input('month: '))
day = int(input('day: '))
principal = float(input('give me a loan amount: '))
rate = float(input('give me an interest rate in decimal form: '))
term = int(input('how many year will this loan be for: '))
comp = int(input('how many times a year will payments be made: '))
monthly = float(input('what will the payment amount be: '))
#DISPLAYS HOW THE SYSTEM TOOK USER INPUT
print('lets take a look at these values')
input()
print('\n', '$', principal,
'\n', (rate*100), '%',
'\n', term, 'years',
'\n', 'paying ', comp, 'times per year',
'\n', 'beginning:', month, '/', day, '/', year,
'\n', 'our monthly payment is $', monthly)
input()
#CALCULATES PERDIEM
perdiem = ((principal * rate) / 365)
print('our perdiem will be $', round(perdiem, 4))
print('with this we can calculate a months payment')
input()
print('first lets try and structure for the first month')
#BELOW IS TESTING TO SEE HOW MANY DAYS ARE IN A BILLING CYCLE
if month == 1 or 3 or 5 or 7 or 8 or 10 or 12:
NumDays = 31
elif month == 4 or 6 or 9 or 11:
NumDays = 30
elif month == 2 and (year % 4) != 0:
NumDays = 28
elif month == 2 and (year % 4) == 0:
NumDays = 29
print('so our first month would have', NumDays, 'days of perdiem')
input()
print('FIRST MONTH PAYMENT')
#BELOW TESTS TO SEE WHAT MONTH NEEDS TO BE DISPLAYED
if month == 12:
NextMonth = month - 11
NextYear = year + 1
else:
NextMonth = month + 1
NextYear = year
#DISPLAYS FIRST MONTHS DATA
print('Date:', NextMonth, '/', day, '/', NextYear)
PayNum = 1
print('Payment: #', PayNum)
print('Payment Amount: $', monthly)
print('Days this cycle:', NumDays)
MonthInt = round((perdiem * NumDays), 2)
print('Months Interest: $', MonthInt)
MonthP = round((monthly - MonthInt), 2)
print('Months Principal: $', MonthP)
balance = round((principal - MonthP), 2)
print('Remainder: $', balance)
input()
basically I would want the same information from the first months pay to be repeated with values being adjusted (paynum +1, nextmonth +1, balance - monthp, etc) until the balance is less than the monthly payment.
I have tried variations of if and while statements but cant seem to structure anything that works. My values will only adjust the one time and cant seem to continually overwrite values.
Help is appreciated on this issue as well as suggestions to better write my existing code.
My personal take is that input() function should be avoided at all costs when learning python: (a) it diverts you from structuring code in a modular way, (b) it is rarely used to applications - the interfaces are usually command line arguments or direct function calls.
The code you supply is a bit hard to follow, even though I appreciate it is linked to COBOL style and culture. The best thing to do is to devise your problem into smaller subtasks and test how they work in separation. This way you will know where your problem is, and it would be easier to focus your question (and attention of people answering).
My understanding is that the core idea of your script is calculating monthly payments and loan amortisation. Consider following code:
# FIXME: missing compound interest
def perdiem(amount, rate):
return (amount * rate) / 365
def days_per_month(month, year):
if month in [1, 3, 5, 7, 8, 10, 12]:
return 31
elif month in [4, 6, 9, 11]:
return 30
elif month == 2:
if (year % 4) == 0:
return 29
else:
return 28
else:
raise ValueError('month expected', month)
def next_month(month, year):
if month == 12:
next_month = 1
next_year = year + 1
else:
next_month = month + 1
next_year = year
return next_month, next_year
def monthly_interest(principal, days, rate):
return perdiem(principal, rate) * days
def monthly_principal(monthly_payment, current_interest_payment):
return monthly_payment - current_interest_payment
def yield_expected_payment_schedule(start_year,
start_month,
initial_amount,
rate,
duration_in_years,
monthly_payment):
year = start_year
month = start_month
amount = initial_amount
for t in range(duration_in_years * 12 + 1):
days = days_per_month(month, year)
interest_due = monthly_interest(amount, days, rate)
if amount > 0:
yield {'balance at month start': amount,
'interest due': monthly_interest(amount, days, rate),
'year': year,
'month': month
}
amount = amount - (monthly_payment - interest_due)
month, year = next_month(month, year)
if __name__ == '__main__':
arg_dict1 = dict(start_year=1965,
start_month=8,
initial_amount=1000,
rate=0.05,
duration_in_years=1,
monthly_payment=85.61)
schedule = list(yield_expected_payment_schedule(**arg_dict1))
print(schedule)
Some follow-up thoughts:
try separate your argument collection, calculation and result presentation as much as possible
when you specifiy amount and duration you just know the monthly payment as an annuity, makes no sense to allow enter them both, consider devising evaluate_monthly_payment()
separate expected payments, amount paid and current amount due to make it more realistic
resort to datatime.date type and corresponding functions for date manipulation.
Hope it's useful.
"""
Hare is the Code for Amortization Schedule Calculator in Python
"""
def MortgageAmortizationSchedule(loan, months, interest):
monthlyPay = loan * (interest * (1 + interest) ** months / ((1 + interest) ** months - 1))
#print(-round(numpy.pmt(interest, months, loan), 2))
payment = monthlyPay
month = 1
monthlyInterest = interest * loan
principal = payment - monthlyInterest
balance = loan - principal
total_interest_paid = 0
print("#" * 105)
print("{0:>15}{1:>20} {2:>20} {3:>20} {4:>20}".format("Payment Month", "Principal Paid", "Interest Paid",
"Monthly Payment", "Mortgage Balance"))
print("#" * 105)
print("{0:>15}{1:>20,.2f} {2:>20,.2f} {3:>20,.2f} {4:>20,.2f}".format(month, principal, monthlyInterest,
payment, balance))
while balance > 0:
monthlyInterest = interest * balance
principal = payment - monthlyInterest
balance = balance - principal
month += 1
total_interest_paid += monthlyInterest
if balance <= 0:
balance = 0
print("{0:>15}{1:>20,.2f} {2:>20,.2f} {3:>20,.2f} {4:>20,.2f}".format(month, principal, monthlyInterest,
payment, balance))
print("#" * 105)
print("Total interest paid will be: ${0:,.2f}".format((payment * month) - loan))
print("Total principal paid will be: ${0:,.2f}".format(loan))
print("#" * 105)
############################## Inputs ##############################
loan = float(input('Enter Loan/Mortgage Amount: '))
years = float(input('Enter Loan Term/Period in years: '))
interest = float(input('Enter annual interest rate for this loan: '))
interest = interest / 12 / 100
months = years * 12
############## Create Amortization Schedule Calculator #############
MortgageAmortizationSchedule(loan, months, interest)
My assignment is to calculate how much money a person would get if his salary started at 1 cent per day and doubled every day.
days = int(input("How many days will you work for pennies a day?"))
total_amount = ((2 ** (days - 1)) / 100)
print("Days Worked | Amount Earned That Day")
for num in range(days):
total_amount = format((2 ** (num) / 100), ',.2f')
print(num + 1, "|", "$", total_amount)
If I enter 15 for days, I can see the salary on each day, but I need the total amount earned over the 15 days.
I need the total amount earned over the 15 days
As a standard for loop example you want summation over each iteration. To achieve this, you initialize variable (total_accumulated in this case) with 0 and then add to this variable each intermediate result from each iteration, after loop is complete you print out final accumulated result like so (minimal editing of your original code):
days = int(input("How many days will you work for pennies a day?"))
total_amount = ((2 ** (days - 1)) / 100)
total_accumulated = 0
print("Days Worked | Amount Earned That Day")
for num in range(days):
current_pay = (2 ** (num) / 100)
total_accumulated += current_pay
total_amount = format(current_pay, ',.2f')
print(num + 1, "|", "$", total_amount)
print("Total accumulated:", str(total_accumulated))
As noted in comment to your question by #NiVeR this can be calculated directly, and this answer is aimed only at example with loops since this looks like classic case of exercise.
Keep track of today salary and previous day salary. previous to calculate today salary and today salary to calculate total
init_sal = .01
total = 0
today_sal = 0
days = int(input("How many days will you work for pennies a day?"))
for x in range(1, days+1):
if x == 1:
today_sal = init_sal
prev_sal = today_sal
else:
today_sal = prev_sal * 2
prev_sal = today_sal
total += today_sal
print ('$', today_sal)
print (total)
I'm trying to solve a problem but I've been working on it for so long and have tried so many things but I'm really new to python and don't know how to get the input I'm after.
The calculator needs to be in a format of a nested loop. First it should ask for the number of weeks for which rainfall should be calculated. The outer loop will iterate once for each week. The inner loop will iterate seven times, once for each day of the week. Each itteration of the inner loop should ask the user to enter number of mm of rain for that day. Followed by calculations for total rainfall, average for each week and average per day.
The main trouble I'm having is getting the input of how many weeks there are and the days of the week to iterate in the program eg:
Enter the amount of rain (in mm) for Friday of week 1: 5
Enter the amount of rain (in mm) for Saturday of week 1: 6
Enter the amount of rain (in mm) for Sunday of week 1: 7
Enter the amount of rain (in mm) for Monday of week 2: 7
Enter the amount of rain (in mm) for Tuesday of week 2: 6
This is the type out output I want but so far I have no idea how to get it to do what I want. I think I need to use a dictionary but I'm not sure how to do that. This is my code thus far:
ALL_DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
total_rainfall = 0
total_weeks = 0
rainfall = {}
# Get the number of weeks.
while True:
try:
total_weeks = int(input("Enter the number of weeks for which rainfall should be calculated: "))
except ValueError:
print("Number of weeks must be an integer.")
continue
if total_weeks < 1:
print("Number of weeks must be at least 1")
continue
else:
# age was successfully parsed and we're happy with its value.
# we're ready to exit the loop!
break
for total_rainfall in range(total_weeks):
for mm in ALL_DAYS:
mm = int(input("Enter the amount of rain (in mm) for ", ALL_DAYS, "of week ", range(total_weeks), ": "))
if mm != int():
print("Amount of rain must be an integer")
elif mm < 0 :
print("Amount of rain must be non-negative")
# Calculate totals.
total_rainfall =+ mm
average_weekly = total_rainfall / total_weeks
average_daily = total_rainfall / (total_weeks*7)
# Display results.
print ("Total rainfall: ", total_rainfall, " mm ")
print("Average rainfall per week: ", average_weekly, " mm ")
print("Average rainfall per week: ", average_daily, " mm ")
if __name__=="__main__":
__main__()
If you can steer me in the right direction I will be so appreciative!
Recommendation: Break the problem into smaller pieces. Best way to do that would be with individual functions.
For example, getting the number of weeks
def get_weeks():
total_weeks = 0
while True:
try:
total_weeks = int(input("Enter the number of weeks for which rainfall should be calculated: "))
if total_weeks < 1:
print("Number of weeks must be at least 1")
else:
break
except ValueError:
print("Number of weeks must be an integer.")
return total_weeks
Then, getting the mm input for a certain week number and day. (Here is where your expected output exists)
def get_mm(week_num, day):
mm = 0
while True:
try:
mm = int(input("Enter the amount of rain (in mm) for {0} of week {1}: ".format(day, week_num)))
if mm < 0:
print("Amount of rain must be non-negative")
else:
break
except ValueError:
print("Amount of rain must be an integer")
return mm
Two functions to calculate the average. First for a list, the second for a list of lists.
# Accepts one week of rainfall
def avg_weekly_rainfall(weekly_rainfall):
if len(weekly_rainfall) == 0:
return 0
return sum(weekly_rainfall) / len(weekly_rainfall)
# Accepts several weeks of rainfall: [[1, 2, 3], [4, 5, 6], ...]
def avg_total_rainfall(weeks):
avgs = [ avg_weekly_rainfall(w) for w in weeks ]
return avg_weekly_rainfall( avgs )
Using those, you can build your weeks of rainfall into their own list.
# Build several weeks of rainfall
def get_weekly_rainfall():
total_weeks = get_weeks()
total_rainfall = []
for week_num in range(total_weeks):
weekly_rainfall = [0]*7
total_rainfall.append(weekly_rainfall)
for i, day in enumerate(ALL_DAYS):
weekly_rainfall[i] += get_mm(week_num+1, day)
return total_rainfall
Then, you can write a function that accepts that "master list", and prints out some results.
# Print the output of weeks of rainfall
def print_results(total_rainfall):
total_weeks = len(total_rainfall)
print("Weeks of rainfall", total_rainfall)
for week_num in range(total_weeks):
avg = avg_weekly_rainfall( total_rainfall[week_num] )
print("Average rainfall for week {0}: {1}".format(week_num+1, avg))
print("Total average rainfall:", avg_total_rainfall(total_rainfall))
And, finally, just two lines to run the full script.
weekly_rainfall = get_weekly_rainfall()
print_results(weekly_rainfall)
I use a list to store average rallfall for each week.
and my loop is:
1.while loop ---> week (using i to count)
2.in while loop: initialize week_sum=0, then use for loop to ask rainfall of 7 days.
3.Exit for loop ,average the rainfall, and append to the list weekaverage.
4.add week_sum to the total rainfall, and i+=1 to next week
weekaverage=[]
i = 0 #use to count week
while i<total_weeks:
week_sum = 0.
print "---------------------------------------------------------------------"
for x in ALL_DAYS:
string = "Enter the amount of rain (in mm) for %s of week #%i : " %(x,i+1)
mm = float(input(string))
week_sum += mm
weekaverage.append(weeksum/7.)
total_rainfall+=week_sum
print "---------------------------------------------------------------------"
i+=1
print "Total rainfall: %.3f" %(total_rainfall)
print "Day average is %.3f mm" %(total_rainfall/total_weeks/7.)
a = 0
for x in weekaverage:
print "Average for week %s is %.3f mm" %(a,x)
a+=1