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.
Related
I'm trying to build a loan calculator that takes in the amount owed and interest rate per month and the down payment put at the beginning and the monthly installments so it can output how many months do you need to pay off your debt. The program works just fine when I enter an interest_rate below 10% but if I type any number for example 18% it just freezes and gives no output. When I stop running the program it gives me these errors:
Traceback (most recent call last):
File "C:\Users\Khaled\PycharmProjects\interest_payment\main.py", line 35, in <module>
months_to_finish = get_months(price) # this returns the number of months from the counter var
File "C:\Users\Khaled\PycharmProjects\interest_payment\main.py", line 6, in get_months
price = price - installments
KeyboardInterrupt
This is my code:
def get_months(price):
counter = 0
price = price - down_payment
while price > 0:
price = price + price * interest_rate
price = price - installments
counter += 1
return counter
if __name__ == '__main__':
price = float(input("Enter price here: "))
interest_rate = float(input("Enter interest rate here: %")) / 100
while interest_rate < 0:
interest_rate = float(input('Invalid interest rate please try again: %')) / 100
down_payment = int(input("Enter your down payment here: $"))
while down_payment > price or down_payment < 0:
down_payment = int(input('Invalid down payment please try again: $'))
choice = input("Decision based on Installments (i) or Months to finish (m), please write i or m: ").lower()
if choice == 'm':
print('m')
elif choice == 'i':
installments = int(input("What's your monthly installment budget: ")) # get the installments
months_to_finish = get_months(price) # this returns the number of months from the counter var
print(f"It will take {months_to_finish} months to finish your purchase.")
else:
print('Invalid choice program ended')
These are the test values:
Enter price here: 22500
Enter interest rate here: %18
Enter your down payment here: $0
Decision based on Installments (i) or Months to finish (m), please write i or m: i
What's your monthly installment budget: 3000
With an initial principal of $22,500, an interest rate of 18%, a down payment of $0, and a monthly payment of $3,000, it will take an infinite number of months to pay off the loan. After one period at 18% interest, you have accrued $4,050 of interest. Since you're only paying $3,000 per period, you're not even covering the amount of new interest, and the total amount you owe will grow forever. You probably want to check somewhere that the monthly payment is greater than the first month's interest. You could modify your code like this:
if installments < (price - down_payment) * interest_rate:
print("The purchase cannot be made with these amounts.")
else:
months_to_finish = get_months(price)
print(f"It will take {months_to_finish} months to finish your purchase.")
l=[]
n=int(input())
i=0
for i in range(n):
l.append(str(input()))
def long(x):
if x>10:
return print(l[i][0]+str(len(l[i])-2)+l[i][-1])
def short(x):
if x<=10:
return print(l[i])
i=0
for i in range(len(l[i])):
long(len(l[i]))
short(len(l[i]))
continue
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
One of my school assignments is to create a program where you can input a minimum number of passengers, a max number of passengers, and the price of a ticket. As the groups of passengers increase by 10, the price of the ticket lowers by 50 cents. At the end it is supposed to show the maximum profit you can make with the numbers input by the user, and the number of passengers and ticket price associated with the max profit. This all works, but when you input numbers that result in a negative profit, i get a run time error. What am i doing wrong? I have tried making an if statement if the profit goes below 0, but that doesn't seem to work. here is my work for you all to see. A lead in the right direction or constructive criticism would be a great help.
#first variables
passengers = 1
maxcapacity = 500
maxprofit = 0
ticketprice = 0
fixedcost = 2500
#inputs and outputs
again = 'y'
while (again == 'y'):
minpassengers = abs(int(input("Enter minimum number of passengers: ")))
maxpassengers = abs(int(input("Enter maximum number of passengers: ")))
ticketprice = abs(float(input("Enter the ticket price: ")))
if (minpassengers < passengers):
minpassengers = passengers
print ("You need at least 1 passenger. Setting minimum passengers to 1.")
if (maxpassengers > maxcapacity):
maxpassengers = maxcapacity
print ("You have exceeded the max capacity. Setting max passengers to 500.")
print ("Passenger Run from", minpassengers, "to", maxpassengers, "with an initital ticket price of $",format (ticketprice, "7,.2f"), "with a fixed cost of $2500.00\n"
"Discount per ticket of $0.50 for each group of 10 above the starting count of", minpassengers, "passengers")
for n in range (minpassengers, maxpassengers + 10, 10):
ticketcost = ticketprice - (((n - minpassengers)/10) * .5)
gross = n * ticketcost
profit = (n * ticketcost) - fixedcost
print ("Number of \nPassengers", "\t Ticket Price \t Gross \t\t Fixed Cost \t Profit")
print (" ", n, "\t\t$", format (ticketcost, "7,.2f"), "\t$", format (gross, "5,.2f"), "\t$", format(fixedcost, "5,.2f"), "\t$", format (profit, "5,.2f"))
if (profit > maxprofit):
maxprofit = profit
maxpass = n
best_ticket = ticketcost
print ("Your max profit is $", format (maxprofit, "5,.2f"))
print ("Your max profit ticket price is $", format (best_ticket,"5,.2f"))
print ("Your max profit number of passengers is", maxpass)
again = input ("Run this again? (Y or N): ")
again = again.lower()
print ("\n")
This is happening because the condition profit > maxprofit never evaluates to True in the situation where your profit is negative, because maxprofit is set to 0 up at the top. This in turn means that best_ticket never gets assigned a value in this case, and so Python can't print it out later.
You could avoid this problem either by setting a default value for best_ticket earlier in the program:
best_ticket = 0
or by adding a condition that you only print out a best ticket price when best_ticket is set:
# Earlier in the program.
best_ticket = None
if best_ticket is not None:
print("Your max profit ticket price is $", format(best_ticket,"5,.2f"))
Also, FYI, the same problem will occur for the maxpass variable.
Your error is telling you the problem
NameError: name 'best_ticket' is not defined
You define best_ticket in this block
if (profit > maxprofit):
maxprofit = profit
maxpass = n
best_ticket = ticketcost
Regardless of the truth of that statement, you reference best_ticket below
print ("Your max profit ticket price is $", format (best_ticket,"5,.2f"))
Your error is probably because the variable you are outputting is defined in a spot that doesn't get executed.
if (profit > maxprofit):
maxprofit = profit
maxpass = n
best_ticket = ticketcost
So, whenever the if condition is False, best_ticket never gets assigned.
Try adding best_ticket = 0 at the top of your code.
ticketprice = abs(float(input("Enter the ticket price: ")))
best_ticket = -1 #nonsense value that warns you whats happening.
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')
This program is supposed to ask the user for the sales for multiple days, write them to a list, then add those entries together and display the sum.
I have the program to the point that it will ask for sales, but my math and the ultimate display is just not coming out right. Any help would be appreciated.
Than you in advance
num_days = 5
def main():
sales = [0] * num_days
index = 0
print('Enter the sales for each day.')
while index < num_days:
print('Sales for day #', index + 1, ': ', sep='', end='')
sales[index] = float(input())
index = index + 1
print('the total is', sales)
main()
Your line print('the total is', sales) prints the entire list of individual sales items.
You want to use print('the total is', sum(sales)), and do that outside of the loop.
Also, you don't need the first print(); simply do
sales[index] = float(input("Sales for day #{}: ".format(index+1)))
And finally, you don't need to build your list of sales items in advance. Something like this would be more Pythonic:
def main(num_days=5):
sales = []
print('Enter the sales for each day.')
for day in range(num_days):
sales.append(float(input("Sales for day #{}: ".format(day+1))))
print('the total is', sum(sales))
main()