how to merge python in loop to get clist - python

Ask for an amount and whether it is taxable; calculate the sales tax and show the tax amount and the total including the tax; allow the user to do the sales tax calculation for multiple items.
Use 9.5% as the sales tax rate.
When the user finishes, tell what the grand total, tax and total, comes to.
Here is the data your demo.
Amount Taxable?
1 $10.00 Y
2 11.00 N
3 1.50 N
4 2.99 Y
5 12.00 Y
here is what i did , I don't know how to get the total in for loop in clist
alist = []
amount = eval(input("How many amount do you want to calculate?"))
for i in range(amount):
alist.append(input("amount" + str(i+1) + ":"))
print(alist)
blist = []
taxable = eval(input("How many amount taxable?"))
for n in range(taxable):
blist.append(input("amount_taxable" + str(n+1) + ":"))
print(blist)
clist = list(zip(alist,blist))
print(clist)
for a,b in clist:
print(a,b)
if b =='Y':
print("grand total" + ":", eval(a)*1.095)
print("tax" + ":" , eval(a)*.095)
print("total_of_taxable" + ":",len(clist)*eval(a)*1.095)
elif b == 'N':
print("not taxable")
print("total_of_not_taxable" + ":",eval(a)*len(clist))

I addition to Redi43's comment you should also
convert the values that you are appending to your lists to ints
not worry about starting the range at 0, as 0 is the default starting value
Something like this is a little better.
alist = []
blist = []
amount = int(input("How many amount do you want to calculate?"))
for i in range(amount):
alist.append(int(input("amount" + str(i+1) + ":")))
taxable = int(input("How many amount taxable?"))
for n in range(taxable):
blist.append(int(input("amount_taxable" + str(n+1) + ":")))
clist = list(zip(alist,blist))
print(clist)

Related

How to use format()?

My teacher gave me this assigment"Write a program that calculates the bill of sale for three items purchased. The cost of each item will be read from the user and stored into variables. The receipt will show the number of items purchased, the cost of each item, the average cost per item, the tax rate (.0825% in Texas), the tax amount, and the total cost" I'was able to do it with basic input and variables but i had some trouble when he asked me to use format() in the code because there's always a different error. Here's my attempt.
cost_1 = float(input("Enter cost of item 1:"))
cost_2 = float(input("Enter cost of item 2:"))
cost_3 = float(input("Enter cost of item 3:"))
cost = ['cost_1', 'cost_2', 'cost_3']
sentence = 'Cost 1: {0} Cost 2: {1} Cost 3: {2}'.format(cost, float['cost_1'], cost, float['cost_2'], cost, float['cost_3'])
print(sentence)
Average_cost = float(cost_1 + cost_2 + cost_3)/3
Total_cost = float(cost_1 + cost_2 + cost_3)
print("Average cost:", Average_cost)
print("Total cost:", Total_cost)
Tax_rate = float(8.25)
print("Tax rate:", Tax_rate)
Taxes = float(Total_cost*Tax_rate/100)
print ("Taxes:",float(Taxes))
Total = Total_cost + Taxes
print("Total:", Total)
I will not give you the answer, but I will explain a couple things you are doing wrong.
cost_1 = float(input("Enter cost of item 1:"))
cost_2 = float(input("Enter cost of item 2:"))
cost_3 = float(input("Enter cost of item 3:"))
# below you are assigning strings to the cost array, you should not have quotes here
cost = ['cost_1', 'cost_2', 'cost_3']
# below you are trying to format with three variables but are passing four.
# you are also trying to access the float function as a dict type.
sentence = 'Cost 1: {0} Cost 2: {1} Cost 3: {2}'.format(cost, float['cost_1'],
cost, float['cost_2'], cost, float['cost_3'])
print(sentence)
# there is no need to constantly float variables that are float
Average_cost = float(cost_1 + cost_2 + cost_3)/3
# agagin
Total_cost = float(cost_1 + cost_2 + cost_3)
print("Average cost:", Average_cost)
print("Total cost:", Total_cost)
# a float number is already a float, you dont need to declare it as float
Tax_rate = float(8.25)
print("Tax rate:", Tax_rate)
Taxes = float(Total_cost*Tax_rate/100)
print ("Taxes:",float(Taxes))
Total = Total_cost + Taxes
print("Total:", Total)
I will give you a little help with the cost list.
items_count = 3
cost = []
for i in range(items_count):
cost.append(float(input("enter price for item %d: " % (i+1))))
Also, there is a function called sum that will add up all the numbers in a list. Here is a tutorial https://www.programiz.com/python-programming/methods/built-in/sum

Weighted Grade book Project

Create a program that will calculate a student’s grade in a class that uses a weighted gradebook.
A weighted system uses percentages to determine how much each assignment category is worth. For this project, use the following percentages:
Project Grades = 30% (weight = .30)
Participation Grades = 20% (weight = .20)
Quizzes = 10% (weight = .10)
Exams = 40% (weight = .40)
Grading scale:
A - 90-100
B - 80-89
C - 70-79
D - 60-69
F - Below 60
Note: You will multiply the average for each of the categories by its weight. The final grade is the sum of the calculated weights.
Can't get the code to the allow the user to enter grades in all 4 categories, because it gets stuck on the first category chosen and the loop just goes on and on without stopping asking for a list of scores. I attempted a loop inside a loop, but it only continued on the first one chosen as well. Need multiple grades entered into all 4 categories which is why I need the program to allow the user to enter grades to the other categories not just the one that is chosen first.
print ("Weighted Grade Calculator ")
name = input("Enter the Student's Name ")
number = input("Enter the Student's Number ")
x = input("Enter Assignment type: ")
c = 'y'
#Loop is in case user wants to calculate another students grade
while c=='y' or c=='Y':
if x >= "quiz" or x >= "Quiz":
input_string = input("Enter a list of scores separated by space ")
#Read ints separated by spaces
lst = input_string.split()
print("Calculating sum of element of input list")
#convert strings to ints and convert map to list
lst = list(map(int, lst))
#Find total and avg
total = sum(lst)
avg_1 = total/len(lst)
elif x >= "project" or x >= "Project":
input_string = input("Enter a list of scores separated by space ")
lst = input_string.split()
print("Calculating sum of element of input list")
lst = list(map(int, lst))
total = sum(lst)
avg_2 = total/len(lst)
elif x >= "participation" or x >= "Participation":
input_string = input("Enter a list of scores separated by space ")
lst = input_string.split()
lst = list(map(int, lst))
total = sum(lst)
avg_3 = total/len(lst)
elif x >= "exam" or x >= "Exam":
input_string = input("Enter a list of scores separated by space ")
lst = input_string.split()
print("Calculating sum of element of input list")
lst = list(map(int, lst))
total = sum(lst)
avg_4 = total/len(lst)
else:
print("error, please try again")
#Finds percentage earned from each category
w_quiz = avg_1 * 0.1
w_project = avg_2 * 0.3
w_participation = avg_3 * 0.2
w_exams = avg_4 * 0.4
total = w_project + w_quiz + w_participation + w_exams
if(total >= 90 and total <=100):
grade = 'A'
elif(total >= 80 and total < 90):
grade = 'B'
elif(total >= 70 and total < 80):
grade = 'C'
elif(total >= 60 and total < 70):
grade = 'D'
elif(total >= 0 and total < 60):
grade = 'F'
print ("Student Name: " + str(name))
print ("Student ID: " + str(number))
print ("Total Weighted Score: " + str(total) + "%")
print ("Letter Grade: " + grade)
c = input("Would you like to calculate another grade? (Y or N): ")
Not sure exactly what you are looking for, but this code will take as much input as you give it and at the end will calculate the average of all totals and its respective letter grade:
def calculate_letter(total):
#function calculates letter grade
if(total >= 90 and total <=100):
grade = 'A'
elif(total >= 80 and total < 90):
grade = 'B'
elif(total >= 70 and total < 80):
grade = 'C'
elif(total >= 60 and total < 70):
grade = 'D'
elif(total >= 0 and total < 60):
grade = 'F'
return grade
print ("Weighted Grade Calculator ")
name = input("Enter the Student's Name ")
number = input("Enter the Student's Number ")
totals = [] #initialize list to append scores to
while True:
project = float(input("Enter the percentage for Projects (numbers only): "))
participation = float(input("Enter the percentage for the Participation (numbers only): "))
quizzes = float(input("Enter the percentage for Quizzes (numbers only): "))
exams = float(input("Enter the percentage for the Final Exam (numbers only): "))
w_project = project * 0.3
w_participation = participation * 0.2
w_quiz = quizzes * 0.1
w_exams = exams * 0.4
total = w_project + w_quiz + w_participation + w_exams
grade = calculate_letter(total) #running the function defined above to evaluate letter grade from total
print ("Total Weighted Score: " + str(total) + "%")
print ("Letter Grade: " + grade)
c = input("Would you like to calculate another grade? (Y or N): ").lower()
totals.append(total)
if c == 'y':
#restarts the loop
continue
else:
#exits the loop
break
print(totals)
final_averaged_score = sum(totals) / len(totals) #finding the average of the list
final_grade = calculate_letter(final_averaged_score)
print ("Student Name: " + str(name))
print ("Student ID: " + str(number))
print ("Final Averaged score: " + str(final_averaged_score))
print ("Final letter grade: " + str(final_grade))

Calculate a total from numbers produced by a for loop (running total)

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)

Program that counts odd numbers and then prints them

So I have question about my homework.
Program must do:
* Asks from user the number of clients ( not negative int number )
* Uses while and gets total number of flowers
* Print final sum to screen.
We have text like:
It's womens day and flowershop decided to give flowers to women. But thing is, only odd number gets them.
So first one gets 1, second one gets nothing, third gets 3 , fifth gets 5 and so on. If you insert 7, then sum of odd numbers is 16 : 1 + 3 + 5 + 7 = 16. If user inserts 8, then sum is also 16 : 1 + 3 + 5 + 7 = 16.
The odd number can't be bigger than number of women.
You have to insert the number of women.
I have done this:
women = int(input("Insert number of buyers: "))
i = 1
sum = 0
while i < women:
i = i + 2
sum = sum + i
print("Total of flowers is: " + str(women))
But it dosent work and my brain is totally out of ideas already :(
Final result must look like this:
Insert number of buyers: 7
Total of flowers is : 16
There are three flaws in your code:
Incrementing i before incrementing sum (meaning the first lady gets 3 flowers)
Using 1 based indices to count the women, but using the wrong loop condition (with women=7 the loop body will not execute if i==7, so it should be i <= women)
Not printing the answer (sum) but the input (women)
Here is a fixed version:
women = int(input("Insert number of buyers: "))
i = 1
sum = 0
while i <= women:
sum = sum + i
i = i + 2
print("Total of flowers is: " + str(sum))
Using a for loop would, to my opinion, be simpler.
women = int(input("Insert number of buyers: "))
sum = 0
for i in range(1,women+1):
if i%2 != 0: # If i is odd
sum += 1
print("Total of flowers is: " + str(sum))
or
women = int(input("Insert number of buyers: "))
sum = sum(i for i in range(1,women+1) if i%2 != 0)
print("Total of flowers is: " + str(sum))
Do this with a list comprehension:
women = int(input("Insert number of buyers: "))
flowers = sum(i for i in range(1, women+1) if i%2 == 1)
print("Total of flowers is:", flowers)
Or using range's step parameter:
women = int(input("Insert number of buyers: "))
flowers = sum(range(1, women+1, 2))
print("Total of flowers is:", flowers)
Alternatively with a loop it could look like this:
women = int(input("Insert number of buyers: "))
flowers = 0
for i in range(1, women+1):
if i%2 == 1:
flowers += i
print("Total of flowers is:", flowers)
Or look like this using a loop and range's step parameter:
women = int(input("Insert number of buyers: "))
flowers = 0
for i in range(1, women+1, 2):
flowers += i
print("Total of flowers is:", flowers)
In future production code, you would go for variant 1 or 2.
Your Simply Revised code:
women = int(input("Insert number of buyers: "));
i = 1;
sum = i;
if women%2==0:
women=women-1;
while i < women:
i = i + 2;
sum = sum + i;
print("Total of flowers is: " + str(sum));

Add integers to a list?

I am trying to ask the user for several values for temperatures of several month by the "monthtemp" input and then add all the values to a list and in the end print out the average for the whole year.
count = 1
loops = int(input("How many years?: "))
listofmonthtemperatures= list()
while count < loops:
for i in range(1,loops+1):
count += 1
year = input("Which is the " + str(i) + ": year?: ")
for j in range (1,13):
monthtemp= int(input("Month " + str(j) + ": "))
listofmonthtemperatures.append(monthtemp)
total= sum(listofmonthtemperatures)
averagetempforyear= total / 12
print("The average temperature for", year, "is", averagetempforyear)
But I get the message year is not defined, but haven't I defined it as whatever the user inputs? And second, will this work? Why can't append simply append the value to listofmonthtemperatures?
I copy/pasted your code and it worked just fine. Maybe this was a typo but your for loops weren't properly indented. I'm running 3.4.3 btw.
count = 1
loops = int(input("How many years?: "))
listofmonthtemperatures= list()
while count < loops:
for i in range(1,loops+1):
count += 1
year = input("Which is the " + str(i) + ": year?: ")
for j in range (1,13):
monthtemp= int(input("Month " + str(j) + ": "))
listofmonthtemperatures.append(monthtemp)
total= sum(listofmonthtemperatures)
averagetempforyear= total / 12
print("The average temperature for", year, "is", averagetempforyear)
Above is the working code with the proper indentation.

Categories