Trying to use loops and add to a variable - python

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.

Related

how to get the average using for loop in python

In this exercise you will create a program that #computes the average of a collection of values #entered by the user. The user will enter 0 as a #sentinel value to indicate that no further values #will be provided. Your program should display an #appropriate error message if the first value entered #by the user is 0.
print("You first number should not be equal to 0.")
total=0
average_of_num=0
i=0
num=input("Enter a number:")
for i in num:
total=total+num
i=i+1
num=input("Enter a number(0 to quit):")
if i==0:
print("A friendly reminder, the first number should not be equal to zero")
else:
average_of_num=total/i
print("Counter",i)
print("The total is: ", total)
print("The average is: ",average_of_num)
See if this works for you.
entry_list = []
while True:
user_entry = int(input("Enter a non Zero number(0 to quit entering: "))
if user_entry == 0:
break
entry_list.append(user_entry)
total = 0
for i in entry_list:
total = total + i
avg = total/len(entry_list)
print("Counter",len(entry_list))
print("The total is: ", total)
print("The average is: ",avg)
If only for loop should be used try this..
num=[int(input("Enter a number:"))]
total=0
for i in num:
if i == 0:
break
total=total+i
x = int(input("Enter a number(0 to quit):"))
if x != 0:
num.append(x)
avg = total/len(num)
print("Counter: ",len(num))
print("The total is: ", total)
print("The average is: ",avg)

How do I gather information from each loop in a while loop python

I want to gather information from a while loop each time it loops over. For example, if you have a while loop that runs forever and encases an input asking for a number, and you add the numbers over time, how should I do that? Example:
while True:
a = int(input("Enter a number "))
a = a + a
Is there any way to do this? Thank you so much!
total = 0
while True:
a = int(input("Enter a number "))
total = total + a
print(f"The total is {total}")
total = 0
while True:
a = int(input("Enter a number"))
total = total + a
print("The sum is ", total)

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

How to add a running total together?

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.

Python Sentinel controlled loop

I was wondering if anyone could help point me in the right direction! I'm a beginner and I'm totally lost. I'm trying to make a Sentinel controlled loop that asks the user to "enter the amount of check" and then ask "how many patrons for this check". After it asks the user then enters it until they type -1.
once user is done inputting it is suppose to calculate the total,tip,tax of each check with an 18% tip for anything under 8 patrons and 20%tip for anything over 9 and a tax rate of 8%.
and then it should add up the Grand totals.
ex: check 1 = 100$
check 2 = 300
check 3 = 20
Total checks = $420
I'm not asking for someone to do it for me but just if you could point me in the right direction, this is all i have so far and im stuck.
As of right now the code is horrible and doesn't really work.
I completed it in Raptor and it worked perfectly I just don't know how to convert it to python
sum1 = 0
sum2 = 0
sum3 = 0
sum4 = 0
sum5 = 0
check = 0
print ("Enter -1 when you are done")
check = int(input('Enter the amount of the check:'))
while check !=(-1):
patron = int(input('Enter the amount of patrons for this check.'))
check = int(input('Enter the amount of the check:'))
tip = 0
tax = 0
if patron <= 8:
tip = (check * .18)
elif patron >= 9:
tip = (check * .20)
total = check + tax + tip
sum1 = sum1 + check
sum2 = sum2 + tip
sum3 = sum3 + patron
sum4 = sum4 + tax
sum5 = sum5 + total
print ("Grand totals:")
print ("Total input check = $" + str(sum1))
print ("Total number of patrons = " + str(sum3))
print ("Total Tip = $" +str(sum2))
print ("Total Tax = $" +str(sum4))
print ("Total Bill = $" +str(sum5))
Your code runs fine, but you have some logic problems.
It appears you're planning to deal with multiple checks at the same time. You'll probably want to use a list for that, and append checks and patrons to it until check is -1 (and don't append the last set of values!).
I think the real issue you're having is that to leave the loop, check must be equal to -1.
If you follow that a bit further down, you continue to work with check, which we now know is -1, regardless of what happened previously in the loop (check is overwritten every time).
When you get to these lines, then you have a real problem:
if patron <= 8:
tip = (check * .18)
elif patron >= 9:
tip = (check * .20)
# This is the same, we know check == -1
if patron <= 8:
tip = (-1 * .18)
elif patron >= 9:
tip = (-1 * .20)
At this point you probably won't be able to do anything interesting with your program.
EDIT: A bit more help
Here's an example of what I'm talking about with appending to a list:
checks = []
while True:
patron = int(input('Enter the amount of patrons for this check.'))
check = int(input('Enter the amount of the check:'))
# here's our sentinal
if check == -1:
break
checks.append((patron, check))
print(checks)
# do something interesting with checks...
EDIT: Dealing with cents
Right now you're parsing input as int's. That's OK, except that an input of "3.10" will be truncated to 3. Probably not what you want.
Float's could be a solution, but can bring in other problems. I'd suggest dealing with cents internally. You might assume the input string is in $ (or € or whatever). To get cents, just multiply by 100 ($3.00 == 300¢). Then internally you can continue to work with ints.
This program should get you started. If you need help, definitely use the comments below the answer.
def main():
amounts, patrons = [], []
print('Enter a negative number when you are done.')
while True:
amount = get_int('Enter the amount of the check: ')
if amount < 0:
break
amounts.append(amount)
patrons.append(get_int('Enter the number of patrons: '))
tips, taxs = [], []
for count, (amount, patron) in enumerate(zip(amounts, patrons), 1):
tips.append(amount * (.20 if patron > 8 else .18))
taxs.append(amount * .08)
print('Event', count)
print('=' * 40)
print(' Amount:', amount)
print(' Patron:', patron)
print(' Tip: ', tips[-1])
print(' Tax: ', taxs[-1])
print()
print('Grand Totals:')
print(' Total amount:', sum(amounts))
print(' Total patron:', sum(patrons))
print(' Total tip: ', sum(tips))
print(' Total tax: ', sum(taxs))
print(' Total bill: ', sum(amounts + tips + taxs))
def get_int(prompt):
while True:
try:
return int(input(prompt))
except (ValueError, EOFError):
print('Please enter a number.')
if __name__ == '__main__':
main()

Categories

Resources