How to add a running total together? - python

I have a homework task to basically create a supermarket checkout program. It has to ask the user how many items they are, they then put in the name and cost of the item. This bit I've worked out fine, however I'm having trouble adding the total together.
The final line of code doesn't add the prices together, it just lists them.
Code so far
print "Welcome to the checkout! How many items will you be purchasing?"
number = int (input ())
grocerylist = []
costs = []
for i in range(number):
groceryitem = raw_input ("Please enter the name of product %s:" % (i+1))
grocerylist.append(groceryitem)
itemcost = raw_input ("How much does %s cost?" % groceryitem)
costs.append(itemcost)
print ("The total cost of your items is " + str(costs))
This is for a homework task for an SKE I'm doing however I'm stumped for some reason!
The expected output is that at the end of the program, it will display a total costs of items added into the program with a £ sign.

You have to loop through list to sum the total:
...
total = 0
for i in costs:
total += int(i)
print ("The total cost of your items is " + str(total)) # remove brackets if it is python 2
Alternative (For python 3):
print("Welcome to the checkout! How many items will you be purchasing?")
number = int (input ())
grocerylist = []
costs = 0 # <<
for i in range(number):
groceryitem = input ("Please enter the name of product %s:" % (i+1))
grocerylist.append(groceryitem)
itemcost = input ("How much does %s cost?" % groceryitem)
costs += int(itemcost) # <<
print ("The total cost of your items is " + str(costs))
Output:
Welcome to the checkout! How many items will you be purchasing?
2
Please enter the name of product 1:Item1
How much does Item1 cost?5
Please enter the name of product 2:Item2
How much does Item2 cost?5
The total cost of your items is 10

You need to declare your costs as int and sum them:
print("Welcome to the checkout! How many items will you be purchasing?")
number = int(input ())
grocerylist = []
costs = []
for i in range(number):
groceryitem = input("Please enter the name of product %s:" % (i+1))
grocerylist.append(groceryitem)
itemcost = input("How much does %s cost?" % groceryitem)
costs.append(int(itemcost))
print ("The total cost of your items is " + str(sum(costs)))
There also seems to be a problem with raw_input. I changed it to input.

Related

How to make a bill by Python

I'm a freshman, and I want to make a bill that write out what I bought, quantity and how much total cash it cost.
customer = str(input("Customer's name: "))
print ("Welcome to our store")
print ("This is our products")
print ("orange 0.5$)
print ("Apple 1$)
print ("Grape 0.5$)
print ("Banana 0.5$)
chooseproducts= int(input("What do you want to buy: "))
For output example. Can you guys help me please.
BILL
Orange 5 2.5$
Apple 3 3$
Grape 2 1$
Total: 10 6.5$
First, your str(input(customer's name: )) code needs to be changed. input() calls need a string as the question, and also the apostrophe has Python think that it is the start of a string.
Also, when you are printing the costs, you need another closing quotation mark. When you are asking the user about what they want to buy, I suppose you want them to input the name of the fruit. Since you have the int() in the front, Python cannot turn a string like "orange" or "grape" into an integer. When people want to buy multiple things, however, they might only put one thing in.
I suppose that this isn't all your code, and you have the part where you calculate the cost. If I were to write this code, I would write it like the following:
customer = str(input("Customer's Name:"))
print ("Welcome to our store")
print ("This is our products")
print ("Orange 0.5$")
print ("Apple 1$")
print ("Grape 0.5$")
print ("Banana 0.5$")
prices = {"orange":0.5,"apple":1,"grape":0.5,"banana":0.5}# I added this so we can access the prices later on
#chooseproducts= int(input("What do you want to buy: "))
# The code below this is what I added to calculate the cost.
productnum = input("How many things do you want to buy: ") # This is for finding the number of different fruits the buyer wants
while not productnum.isdigit():
productnum = input("How many different products do you want to buy: ")
productnum = int(productnum)
totalprice = 0
totalfruit = 0
print(' BILL')
for i in range(productnum):
chosenproduct = input("What do you want to buy: ").lower()
while not chosenproduct in ['orange','apple','banana','grape']:
chosenproduct = input("What do you want to buy: ").lower()
fruitnum = input("How many of that do you want to buy: ")
while not fruitnum.isdigit():
fruitnum = input("How many of that do you want to buy: ")
fruitnum = int(fruitnum)
totalfruit += fruitnum
price = fruitnum * prices[chosenproduct]
totalprice += price
startspaces = ' ' * (11 - len(chosenproduct))
endspaces = ' ' * (5 - len(str(fruitnum)))
print(chosenproduct.capitalize() + startspaces + str(fruitnum) + endspaces + str(price) + '$')
print('Total: ' + str(totalfruit) + ' ' * (5 - len(str(totalprice))) + str(totalprice) + '$')
Please make sure you understand the code before copying it, thanks!

Im new to python and having an issue with my list being out of range

so im getting a list index out of range here:
for i in range(len(empNr)):
print(empNr[i], rate[i], hrs[i], wkPay[i])
and I haven't really figured lists out, so I may just be confused and am unable to understand why i would be out of range. here the rest of the code below. thanks!
SENTINEL = 0
wkTotal = payHigh = wkPay = empHigh = 0
empNr = []
rate = []
hrs = []
wkPay = []
i = 0
empNr.append(input("Input first employee number: "))
#iteration if 0 is entered it should stop
while (empNr[i] != str(SENTINEL)):
rate.append(int(input("Input rate: ")))
hrs.append(int(input("Input hours: ")))
wkPay.append(rate[i] * hrs[i])
i = i + 1
empNr.append(input("Input employee number or '0' to stop: "))
#calculations using list functions
wkTotal = sum(wkPay)
payHigh = max(wkPay)
wkAvg = float(wkTotal) / len(empNr)
#output summary for pay calculator
print("\n\n Data entry complete " +" \n --------------------------------------")
print("\n Employee Number Pay Rate Hours worked Pay ")
print("--------------------------------------------------------")
for i in range(len(empNr)):
print(empNr[i], rate[i], hrs[i], wkPay[i])
print("Summary: ")
print("WEEK TOTAL: ", str(wkTotal))
print("EMPLOYEE HIGH: ", str(empHigh))
print("PAY HIGH: ", str(payHigh))
print("WEEK AVERAGE: ", str(wkAvg))
empNr.append(input("Input employee number or '0' to stop: ")) this line appends '0' to empNr. But it has no corresponding values for rate, hrs or wkPay. Meaning rate, hrs or wkPay these have one element less than that of empNr. A quick fix (but not recommended) would be to loop for rate or hrs instead of empNr. So your code would be:
for i in range(len(rate)):
print(empNr[i], rate[i], hrs[i], wkPay[i])
A better fix would be:
i = 0
inp = input("Do you want to add anew record? Y/n: ")
while (inp == "Y"):
empNr.append(input("Input first employee number: "))
rate.append(int(input("Input rate: ")))
hrs.append(int(input("Input hours: ")))
wkPay.append(rate[i] * hrs[i])
i = i + 1
inp = input("Do you want to add anew record? Y/n: ")
So while I enter 'Y' I can add new entries and length of each empNr, rate, hrs, wkPay would match. If I enter anything other than Y, the loop will terminate and the lengths will still remain the same...
SENTINEL = 0
wkTotal = payHigh = wkPay = empHigh = 0
empNr = []
rate = []
hrs = []
wkPay = []
i = 0
empNr.append(input("Input first employee number: "))
#iteration if 0 is entered it should stop
while (empNr[i] != str(SENTINEL)):
rate.append(int(input("Input rate: ")))
hrs.append(int(input("Input hours: ")))
wkPay.append(rate[i] * hrs[i])
i = i + 1
empNr.append(input("Input employee number or '0' to stop: "))
#calculations using list functions
wkTotal = sum(wkPay)
payHigh = max(wkPay)
wkAvg = float(wkTotal) / len(empNr)
#output summary for pay calculator
print("\n\n Data entry complete " +" \n --------------------------------------")
print("\n Employee Number Pay Rate Hours worked Pay ")
print("--------------------------------------------------------")
for i in range(len(empNr)-1):
print(empNr[i], rate[i], hrs[i], wkPay[i])
print("Summary: ")
print("WEEK TOTAL: ", str(wkTotal))
print("EMPLOYEE HIGH: ", str(empHigh))
print("PAY HIGH: ", str(payHigh))
print("WEEK AVERAGE: ", str(wkAvg))
Please use the above.
Lets say the list had 2 employee details. According to your solution len(empNr) gives 3. The range function will make the for loop iterate for 0,1 and 2. Also one mistake you did was even for the exiting condition when u r accepting the value for 0 you had used the same list which increases the count of the list by 1 to the no. of employees. Hence do a -1 so that it iterates only for the employee count

output for min/max sometimes correct, other times not

So I'm writing a basic program, and part of the output is to state the lowest and highest number that the user has entered. For some reason, the min and max are correct some of the time, and not others. And I can't figure out any pattern of when it's right or wrong (not necessarily when lowest number is first, or last, etc). Everything else works perfectly, and the code runs fine every time. Here is the code:
total = 0
count = 0
lst = []
while True:
x = input("Enter a number: ")
if x.lower() == "done":
break
if x.isalpha():
print("invalid input")
continue
lst.append(x)
total = total + int(x)
count = count + 1
avg = total / count
print("The total of all the numbers your entered is: " + str(total))
print("You entered " + str(count) + " numbers.")
print("The average of all your numbers is: " + str(avg))
print("The smallest number was: " + str(min(lst)))
print("The largest number was: " + str(max(lst)))
Any ideas? Keep in mind I'm (obviously) pretty early on in my coding study. Thanks!
If, at the end of your program, you add:
print("Your input, sorted:", sorted(lst))
you should see the lst in the order that Python thinks is sorted.
You'll notice it won't always match what you think is sorted.
That's because you consider lst to be sorted when the elements are in numerical order. However, the elements are not numbers; when you add them to lst, they're strings, and Python treats them as such, even when you call min(), max(), and sorted() on them.
The way to fix your problem is to add ints to the lst list, by changing your line from:
lst.append(x)
to:
lst.append(int(x))
Make those changes, and see if that helps.
P.S.: Instead of calling str() on all those integer values in your print statements, like this:
print("The total of all the numbers your entered is: " + str(total))
print("You entered " + str(count) + " numbers.")
print("The average of all your numbers is: " + str(avg))
print("The smallest number was: " + str(min(lst)))
print("The largest number was: " + str(max(lst)))
you can take advantage of the fact that Python's print() function will print each argument individually (separated by a space by default). So use this instead, which is simpler and a bit easier to read:
print("The total of all the numbers your entered is:", total)
print("You entered", count, "numbers.")
print("The average of all your numbers is:", avg)
print("The smallest number was:", min(lst))
print("The largest number was:", max(lst))
(And if you want to, you can use f-strings. But you can look that up on your own.)
You convert your input to int when you are adding it to the total, but not when you are finding the min and max.
When given strings, min and max return values based on alphabetical order, which may sometimes happen to correspond to numerical size, but in general doesn't.
All you need to do is to append input as ints.
total = 0
count = 0
lst = []
while True:
x = input("Enter a number: ")
if x.lower() == "done":
break
if x.isalpha():
print("invalid input")
continue
lst.append(int(x)) # this should fix it.
total = total + int(x)
count = count + 1
avg = total / count
You might also want to use string formatting to print your answers:
print(f"The total of all the numbers your entered is: {total}")
print(f"You entered {count} numbers.")
print(f"The average of all your numbers is: {avg}")
print(f"The smallest number was: {min(lst)}")
print(f"The largest number was: {max(lst)}")

Trying to use loops and add to a variable

I want to create a while loop to prompt the user if they would like to enter a living cost. The user would input 'y' for yes and the loop would proceed.
I this loop I would like to add up all the living expense entered and once the loop ends to store to the total amount in total_living.
Example would be
l_cost = input('Enter living cost? y or n ')
while l_cost != 'n' (loop for living cost)
totat_living = (keeps adding until I say all done
l_cost = input('Enter living cost? y or n ')
Other while and for loops for different scenarios
total_exp = total_living + total_credit + total_debt ect ect
I just need a little help with this as to how to add up multiple values and then maintaining the total value for the loop that I am in.
If someone could point me to an example of a function or loop that is similar or tell me where to look that would be great!
You may try using while as below:
flag = input ("wish to enter cost; y or n" )
total=0
While flag != 'n':.
cost = int(input ("enter cost: "))
total = total + cost
flag = input("more ?? Y or n")
print(total)
total_cost = 0.0
prompt = 'Enter a living cost? y or n: '
answer = input(prompt)
while answer.lower() != 'n':
cost = input('Enter your cost: ')
total_cost = total_cost + float(cost)
answer = input(prompt)
print('Total cost is $' + str(total_cost))
def checkout():
total = 0
count = 0
moreItems = True
while moreItems:
price = float(input('Enter price of item (0 when done): '))
if price != 0:
count = count + 1
total = total + price
print('Subtotal: $', total)
else:
moreItems = False
average = total / count
print('Total items:', count)
print('Total $', total)
print('Average price per item: $', average)
checkout()
Note
Try to convert this example to your problem.

Running a loop (x) times

I am trying to loop an input for a selected amount of time "enter how may ingredients you want:" say if the user inputs 5 then a loop "ingredients" will run 5 times for them to enter their ingredients. Sorry if it seems like a basic question, but I'm quite new to this. Thanks for any answers :).
a=input("hello, welcome to the recipe calculator \nenter your recipe name, number of people you will serve and the list of ingredients \n1.retrive recipe \n2.make recipe \noption:")
if a=="2":
print("now enter the name of your recipe")
f=open('c:\\username_and_password.txt', 'w')
stuff = input("create name:")
nextstuff = (int(input("enter number of people:")))
nextstufff = (int(input("enter how many ingredients you want:")))
for (nextstufff) in range(0, 10): #I have put 0, 10 because the user probably wont put more than 10 ingredients. But there's probably a much better way?
print ("ingredient") + (nextstufff) #what am I doing wrong in this for loop
nextstuffff = (int(input("so how much of\n" + nextstufff + "would you like:")))
f.write(str(stuff + "\n") + str(nextstuff) + str(nextstufff))
f.close()
It would be difficult to cleanly answer your question(s) -- so I'll focus specifically on the looping over ingredients question. This should get you pointed in the right direction.
def read_items(prompt):
items = []
while True:
answer = raw_input('%s (blank to end): ' % prompt)
if not answer:
return items
items.append(answer)
ingredients = read_items('enter ingredients')
counts = []
for item in ingredients:
cnt = raw_input('how much of %s:' % item)
counts.append(int(cnt))
print zip(ingredients, counts)
it's not print ("ingredient") + (nextstufff), change it to print ("ingredient:", nextstufff).
Or you can use string formatting:
print ("ingredient: %d"%nextstufff)

Categories

Resources