I have to be able to calculate the revenu per month depending on the number of goats sold per month knowing that every month I sell 20% of the goats I had initially in January. When I try to calculate it through my price_list I can only get 400$ and not the 300$ for the corresponding months.
The variable d is there to know whether or not the month starts with a vowel. If it does d= "d'" and if not d="de".
I have been going at it for a week and can't seem to find a solution for neither of my two problems.
Help would be really appreciated !!!
goats=int(input("Enter the number of goats at the beginning of january :"))
year= ["january","february","march","april","may","june","july","august","september","october","november","december"]
vowels = "aeiouy"
price_list = [400,400,400,400,300,300,300,300,300,300,400,400]
d=""
if goats >0:
for month in range(len(year)):
goats_left = int(goats*0.8)
goats_sold = goats - goats_left
goats = goats_left
print("At the of the month of {0} {1} , we will have {2} goats left, monthly revenu: {3} $".format(d,year[month],goats,price_list[i]))
else:
print("The number entered is not valid {0}.format(goats))
goats=int(input("Enter the number of goats at the beginning of january :"))
print("\n")
print("ANNUAL REVENUE ........................................................ :".format())
print(goats_sold_list)
My first suggestion would be to use enumerate as a more pythonic way to iterate over your list and get it's index. I also don't understand your use of d anywhere so perhaps clarify how you intended it to be used.
Finally, l don't see i or goats_sold_list declared anywhere.
This should be a starting point for improvement:
goats = int(input("Enter the number of goats at the beginning of january :"))
year = ["january","february","march","april","may","june","july","august","september","october","november","december"]
vowels = "aeiou"
price_list = [400,400,400,400,300,300,300,300,300,300,400,400]
d=""
goats_sold_list = []
if goats >0:
for index, month in enumerate(year):
#int() always rounds down, i.e 0.8 goes to 0
goats_left = int(goats*0.8)
goats_sold = goats - goats_left
goats = goats_left
goats_sold_list.append(goats_sold)
print("At the of the month of {0} {1} , we will have {2} goats left, monthly revenu: {3} $".format(d,month,goats,price_list[index]))
else:
print("The number entered is not valid {0}.format(goats)")
goats=int(input("Enter the number of goats at the beginning of january :"))
print("\n")
print("ANNUAL REVENUE ........................................................ :".format())
print(goats_sold_list)
I don't see a definition for [i] in price_list[i], barring some outside definition, I think that should be price_list[month].
I don't see d being set at any point, you might need to have some line of code setting d to some value based on the first letter of the month.
Related
The goal is:
Starting at the year 1900 count every year to input year.
Then run it through leap year formula.
Print only years that are leap years.
I can get the counter to work and print, I can get leap year formula to work, 1 year at a time. I would like to combine both. What am I doing incorrectly?
counter = 1900
my_list = []
my_list = [str(item) for item in input("Enter ending year: ")]
while counter < my_list:
counter += 1
my_list.append(counter) # adds each value to list
if str(my_list) % 4 == 0 and str(my_list) % 100 != 0 or str(my_list) % 400 == 0:
print(str(my_list)[1:-1] + " is a leap year")
else:
pass
As you seem to be quite new to python and your code is not working I will just guess what you want to do and propose an answer
begin = 1900
end_as_str = input("Enter ending year: ") # input returns a string
end_as_int = int(end_as_str) # therefore you have to cast it to an int
for year in range(begin, end_as_int): # to give it here to range
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
print(str(year) + " is a leap year!")
Be aware that this will not include the end year
as range(1,4) for example would give you the numbers 1, 2 and 3 in an iterator, so the end is not included
I hope that you are a not submitting this right away to a teacher like this, and without going through it and understanding it, as I do not want to be the guy doing assignments for you. If it helps you to better understand python I am happy ;)
Edit: If you do not understand something from my solutin (for example range) try googling for it or search on youtube, you will likely find an explanation
I was trying to print the output under the 2nd for loop (enter the amount Of $20: ...), but I am getting 0. How to fix this issue? The user gets amount of $20 : 1, and amount of $2.00: 2, when they input 22 from keyboard.
Code:
denomitions={"$20.00":0,
"$10.00":0,
"$5.00":0,
"$2.00":0,
"$1.00":0,
"$0.25":0,
"0.10":0,
"0.5":0}
dividers = [2000,1000,500,200,100,25,10,5]
number = float(input("please enter the amount for change:").strip("$"))
#convert dollar to cents
change = int(number*100)
for i in range(len(denomitions)):
amount = int(change/dividers[i])
change= change- amount * dividers[i]
#print the result out
index= float(dividers[i] / 100.00)
print(index,":",amount)
#print the result out
for k in denomitions:
print("amount of "+str(k),amount)
denomitions={"$20.00":0,
"$10.00":0,
"$5.00":0,
"$2.00":0,
"$1.00":0,
"$0.25":0,
"0.10":0,
"0.5":0}
dividers = [2000,1000,500,200,100,25,10,5]
#add an empty list
amount_list = []
number = float(input("please enter the amount for change:").strip("$"))
#convert dollar to cents
change = int(number*100)
for i in range(len(denomitions)):
amount = int(change/dividers[i])
change= change- amount * dividers[i]
#print the result out
index= float(dividers[i] / 100.00)
print(index,":",amount)
#fill the list with the amount at index i
amount_list.append(amount)
#print the result out
i = 0
for k in denomitions:
#now you can retrieve the amount from the list if you keep the same index
print("amount of "+str(k), str(amount_list[i]))
i += 1
The problem is that in the second for loop, it picks up the amount equal to the last round of the previous for loop. At the end of the first loop amount = 0, therefore you will always get zero when printing amount in the second for loop.
Im allowed to use Numpy for the task.
I need to show the total sales in a month with two lists: dates and sales.
My approach is to make a list of all sales during a month by stripping the month off the date, creating a 2D matrix and adding the values that check for each month.
import numpy as np
dates = ["02/01/19", "03/02/19"]
sales = ["10.50", "12.20"]
month = [x.strip("0").split("/")[0] for x in dates]
monthsales = np.vstack((month, sales)).astype(np.float)
def monthlysales():
jan = []
for i in monthsales[0, 0:]:
if i == 1:
jan.append()
s = input("Pick month: ")
if s == "1":
print("Sales total for Jan is:", np.sum(jan), "USD")
else:
print("Not a valid month")
return
print(monthsales)
print(monthlysales())
The problem is that I dont know what to append so that it takes the second row of my matrix, which would complete the code
A solution keeping your logic:
Here I loop over the months (as you did, but here using enumerate), and look for when the month is equal to 1. Using enumerate allows us to know the column number of when the month equals 1 (id). Then it's just a matter of appending the sales (row 1) at the month we're interested in (id)
import numpy as np
dates = ["02/01/19", "03/02/19"]
sales = ["10.50", "12.20"]
month = [x.strip("0").split("/")[0] for x in dates]
monthsales = np.vstack((month, sales)).astype(np.float)
def monthlysales():
jan = []
# Loop over months with enumerate
for id, month in enumerate(monthsales[0]):
if month == 1:
# Append sales (row 1) at column id
jan.append(monthsales[1, id])
s = input("Pick month: ")
if s == "1":
print("Sales total for Jan is:", np.sum(jan), "USD")
else:
print("Not a valid month")
print(monthsales)
print(monthlysales())
Of course, since you're allowed to use numpy you could have avoided any looping altogether. Consider the following line:
monthsales[1, monthsales[0] == 1].sum()
This sums up the sales for all the January months in one line. No loops. For any reasonable amount of data this will be considerably quicker than the solution with enumerate.
Looking more like your initial solution you could have had:
def monthlysales():
s = int(input("Pick month: "))
if s >= 1 and s <= 12:
monies = monthsales[1, monthsales[0] == s].sum()
print("Sales total for month {} is {} USD".format(s, monies))
else:
print("Not a valid month")
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
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()