I am trying to create a cash register program. My objective is for all the products be added and the final price be found. How can I reach this goal without knowing the values previously? Below is my code. Thanks in advance for any help it is greatly appreciated
responses = {}
polling_active = True
print("Welcome to the cash register. Insert your product name and price to be able to calculate your final total")
total = 0
while polling_active:
product = input("\nProduct Name: ")
total += float(input("Price: "))
responses[product] = total
repeat = input("Is this your final checkout? (Yes/No)")
if repeat == 'no':
polling_active = True
elif repeat == 'No':
polling_active = True
elif repeat == 'Yes':
polling_active = False
elif repeat == 'yes':
polling_active = False
else:
print("That operation is invalid")
print("\n---Final Checkout---")
for product, price in responses.items():
print(product + " is $" + str(total))
print("\n---Total Price---")
print("Store Price is: ")
print("$" + str(total))
print("\n---Tax Price---")
print("Your price with tax is: ")
total = total * 1.13
print("$" + "{0:.2f}".format(float(total)))
print("\nThank you for shopping with us! Have a great day!")
I understand the with my current code, total will not allow me to add any products but that is just currently a place holder
Here is the code that you need:
responses = {}
polling_active = True
print("Welcome to the cash register. Insert your product name and price to be able to calculate your final total")
while polling_active:
product = input("\nProduct Name: ")
price = float(input("Price: "))
responses[str(product)] = price
repeat = raw_input("Is this your final checkout? (Yes/No)")
if repeat.lower() == 'no':
polling_active = True
elif repeat.lower() == 'yes':
polling_active = False
else:
print("That operation is invalid")
print("\n---Final Checkout---")
for product, price in responses.items():
print(product + " is $" + str(price))
print("\n---Total Price---")
print("Store Price is: ")
total= sum(responses.values())
print("$" + str(total))
print("\n---Tax Price---")
print("Your price with tax is: ")
total = total * 1.13
print("$" + "{0:.2f}".format(float(total)))
print("\nThank you for shopping with us! Have a great day!")
Output:
integer:
float:
Related
im learning python and for my homework i wanna make a food ordering program and get the receipt of the products purchased with the prices for the total. im struggling to get the billing process as i cannot get all the products chosen by the user displayed on the receipt
import datetime
x = datetime.datetime.now()
name = input("Enter your name: ")
address = input("Enter your address: ")
contact = input("Enter your phone number: ")
print("Hello " + name)
print("*"*31 + "Welcome, these are the items on on the menu."+"*" * 32 )
print("Menu:\n"
"1.Burger:150.\n"
"2.Fried Momo:120.\n"
"3.coffee:60.\n"
"4.Pizza:180.\n"
"5.Fried Rice:150.\n"
"6.French Fries:90.\n"
"7.Steamed Dumplings:150.\n"
"8.Chicken drumsticks:120.\n"
"9.Chicken Pakoras:120.\n"
"10.American Chop Suey:200.\n")
prices = {"1.Burger":150,
"2.Fried Momo":120,
"3.coffee":60,
"4.Pizza":180,
"5.Fried Rice":150,
"6.French Fries":90,
"7.Steamed dumplings":150,
"8.Chicken drumsticks":120,
"9.Chicken Pakoras":120,
"10.American Chop Suey":200
}
continue_order = 1
total_cost, total = 0, 0
cart = []
while continue_order != 0:
option = int(input("Which item would you like to purchase?: "))
cart.append(option)
if option >= 10:
print('we do not serve that here')
break
elif option == 1:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: ₹" + str(total))
elif option == 2:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 3:
quantity = int(input("Enter the quantity: "))
total = quantity * 60
print("The price is: " + str(total))
elif option == 4:
qquantity = int(input("Enter the quantity: "))
total = quantity * 180
print("The price is: " + str(total))
elif option == 5:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: " + str(total))
elif option == 6:
quantity = int(input("Enter the quantity: "))
total = quantity * 90
print("The price is: " + str(total))
elif option == 7:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: " + str(total))
elif option == 8:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 9:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 10:
quantity = int(input("Enter the quantity: "))
total = quantity * 200
print("The price is: " + str(total))
total_cost += total
continue_order = int(input("Would you like another item? enter Yes--> (1) or--> No (0):"))
print('='*30)
print('='*30)
print("Your receipt:\n")
print("Date: " + str(x))
print("Name: " + name.title())
print("Adress: " + address)
print("Contact number: " + contact)
for option in cart:
print ("Item: %s. Price: %s") % (option, prices[option])
print("Quantity: ",quantity)
print("Total Price: ", total_cost)
print('='*30)
print("Thank you for shopping here, have a great day ")
print('='*30)
but i get an error line 95, in
print ("Item: %s. Price: %s") % (option, prices[option])
KeyError: 1
any solution or better ways to improve the code would be really great
Try using F-Strings. They let you format text far more easily. Here's an example.
x = "hello!"
print(f"shr4pnel says {x}")
>>> shr4pnel says hello!
The problem in this case is that option == 1. 1 isn't a key in the dictionary so nothing is output. Hope this helps. This is because the dictionary does not have 1 as a key. To access the item the dictionary would have to be formatted like this.
prices = {1: "burger", 2: "hot dog"}
print(prices[1])
>>> burger
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
d = {}
temp = 10000
total = 0
def Expanse_calculator():
global temp
buy = True
while buy == True:
x = input("Enter the expenditure name:")
if x in d.keys():
price =float(input(f" Enter the '{x}' amount:"))
if temp>=price:
d[x]+=price
temp-=price
else:
print("insufficint found")
break
else:
price =float(input(f"Enter the '{x}'amount:"))
if temp>=price:
d[x]=price
temp-=price
else:
print("insufficint found")
break
total=sum(d.values())
while True:
ip = input("If you want to add any more expenditure [YES|NO]:").lower()
if ip == 'no':
buy = False
break
elif ip == 'yes':
Expanse_calculator()
else:
print("Invalid Entry")
Expanse_calculator()
print(total)
Above is my sample code
While entering 'no' to my query in while loop its not terminating in first attempt
output i'm getting:
Enter the expenditure name:asd
Enter the 'asd'amount:123
If you want to add any more expenditure [YES|NO]:yes
Enter the expenditure name:asf
Enter the 'asf'amount:124
If you want to add any more expenditure [YES|NO]:no
If you want to add any more expenditure [YES|NO]:no
iam new to python plz help.
d = {}
temp = 10000
total = 0
def Expanse_calculator():
global temp,total
buy = True
while buy == True:
x = input("Enter the expenditure name: ")
if x in d.keys():
price =float(input(f" Enter the '{x}' amount: "))
if temp>=price:
d[x]+=price
temp-=price
else:
print("insufficient funds")
break
else:
price =float(input(f"Enter the '{x}'amount: "))
if temp>=price:
d[x]=price
temp-=price
else:
print("insufficient funds")
break
total=sum(d.values())
while True:
ip = input("If you want to add any more expenditure [YES|NO]:").lower()
if ip == 'no':
buy = False
break
elif ip == 'yes':
Expanse_calculator()
else:
print("Invalid Entry")
print(total)
quit()
Expanse_calculator()
I'm trying to get Python to print every user input on a while loop. Essentially the user enters a value, then is asked again and again for a value until user decides to stop entering values. The code prints the sum of the values but also each individual value inputted.
I managed to get everything working except printing each individual value. Any help is really appreciated!
another = True
init_bal = 1000
deposit = 0
while another:
another += 1
deposit += int(input("Enter amount: "))
print(f'${deposit} deposited!')
another = int(input("Make another deposit? Yes=1, No=2 "))
if another == 1:
another = True
else:
print(f'Your initial balance was ${init_bal}.')
print(f'You have deposited a total of ${deposit}.')
print(f'Your final balance is ${init_bal + deposit}.')
break
another = True
init_bal = 1000
deposit = 0
toatl_deposits = []
while another:
another += 1
deposit += int(input("Enter amount: "))
toatl_deposits.append(deposit)
print(f'${deposit} deposited!')
another = int(input("Make another deposit? Yes=1, No=2 "))
if another == 1:
another = True
else:
print(f'Your initial balance was ${init_bal}.')
print(f'You have deposited a total of ${deposit}.')
print(f'Your final balance is ${init_bal + deposit}.')
print('following are list of user inputs: ')
for i in toatl_deposits:
print(f'${i}')
break
Try this,
from datetime import datetime
init_bal = 1000
deposit = 0
transactions = []
while True:
deposit += int(input("Enter amount: "))
print(f'${deposit} deposited!')
transactions.append({'time': datetime.now(), 'amount': deposit})
try:
another = int(input("Make another deposit (Yes=1, No=any)?"))
except:
break
if another != 1:
break
print(f'Your initial balance was ${init_bal}.')
print(f'You have deposited a total of ${deposit}.')
print('Your transactions history:')
for transaction in transactions:
print('Deposited $' + str(transaction['amount']) + ' at ' + str(transaction['time']))
print(f'Your final balance is ${init_bal + deposit}.')
If you write this code by yourself you could understand to easily break it down and print out like this.
another = True
init_bal = 1000
deposit = 0
while another:
another += 1
amount = input("Enter amount: ")
deposit += int(amount)
print("Deposit Amount = " , amount)
print(f'${deposit} deposited!')
another = int(input("Make another deposit? Yes=1, No=2 "))
if another == 1:
another = True
else:
print(f'Your initial balance was ${init_bal}.')
print(f'You have deposited a total of ${deposit}.')
print(f'Your final balance is ${init_bal + deposit}.')
break
I have this code and it doesn't run at all. It is a list of objects, and each object has a two dimensional list in it. It is not executing the code to even display just the flightNo element. I've made a method to display the 2d list in the object, but nothing happens. I tested with a simple print('Hello') at the end and that does work. Can someone tell me what could be wrong here?
EDIT: Full code at: https://onlinegdb.com/HJPqXWXWU
elif a == 3:
for i in range(len(FlightList)):
print(FlightList[i].flightNo)
req = input('Enter flight number to buy tickets: ')
for Flight in FlightList:
if Flight.flightNo == req:
for a in range(len(Flight.seats)):
for b in range(len(Flight.seats[a])):
print(Flight.seats[a][b], end=" ")
print()
qty = int(input('Enter number of tickets'))
Flight.buyTicket(one, qty)
print("Hello")
I have also tried a different method to display flightNo, no execution again:
for Flight in FlightList:
print(Flight.flightNo)
re4 = input('Enter flight number to view seats: ')
for i in FlightList:
if i.flightNo == re4:
for a in range(len(i.seats)):
for b in range(len(i.seats[a])):
print(i.seats[a][b], end=" ")
print()
Here is the working code that I modified the location of calling the method and assigning to the variable because every time we have to create a new instance of the class to save data properly and we should not clear the list that's why I changed the position outside of the loop. And this I working properly. for my basic testing. I can improve if you need. and kept your code in the comment's so you can see the change.
import sys
class Flight:
def __init__(self):
self.flightNo = "None"
self.planeType = "None"
self.destination = "None"
self.w = self.h = 0
self.seats = [["None" for x in range(self.w)] for y in range(self.h)]
self.depDate = "None"
self.depTime = "None"
self.eta = "None"
self.ticketsSold = 0
self.pricePerTicket = 0.0
def displayDetails(self):
print('Flight No: ', self.flightNo,
'\nPlane Type: ', self.planeType,
'\nDestination: ', self.destination,
'\nDeparture Date: ', self.depDate,
'\nDeparture Time: ', self.depTime,
'\nETA: ', self.eta,
'\nTickets Sold: ', self.ticketsSold,
'\nPrice: ', self.pricePerTicket, '\n\n')
def totalSales(self):
return print("Total number of tickets sold: ", self.ticketsSold,
"\nTotal sales: ", (self.ticketsSold * self.pricePerTicket))
def buyTicket(self, quantity):
quantity = int(input("Enter number of tickets required: "))
cost = quantity * self.pricePerTicket
for v in range(len(self.seats)):
for j in range(len(self.seats[v])):
if quantity > len(self.seats) * len(self.seats[v]):
print("Lessen the number of tickets")
break
if self.seats[v][j] == "\\__/":
self.seats[v][j] = "\\AA/"
quantity -= 1
if quantity == 0:
break
if quantity == 0:
break
print(quantity, "tickets bought for $", cost,
"\nSeats assigned", )
self.ticketsSold += quantity
# one = Flight()
ans = True
FlightList = []
while ans:
print("----------------------------- \n1. Add a flight \n2. Remove a flight \n3. Sell Tickets",
"\n4. Display seat info \n5. Display total sales for flight \n6. Display flight info",
"\n7. Display all flight's info \n0. Quit")
a = int(input("Enter number: "))
#FlightList = []
if a == 1:
one = Flight()
one.flightNo = input('Enter flight number: ')
one.planeType = input('Enter plane type: ')
one.destination = input('Enter destination: ')
one.w = int(input('Enter number of columns in flight: '))
one.h = int(input('Enter number of rows in flight: '))
one.seats = [["\\__/" for x in range(one.w)]
for y in range(one.h)]
one.depDate = input('Enter departure date: ')
one.depTime = input('Enter departure time: ')
one.eta = input('Enter ETA: ')
one.ticketsSold = int(input('Enter number of tickets sold: '))
one.pricePerTicket = float(input('Price: '))
FlightList.append(one)
elif a == 2:
rem = input('Enter flight number to remove: ')
for i in FlightList:
if i.flightNo == rem:
del FlightList[FlightList.index(i)]
elif a == 3:
for i in range(len(FlightList)):
print(FlightList[i].flightNo)
req = input('Enter flight number to buy tickets: ')
for Flight in FlightList:
if Flight.flightNo == req:
for a in range(len(Flight.seats)):
for b in range(len(Flight.seats[a])):
print(Flight.seats[a][b], end=" ")
print()
qty = int(input('Enter number of tickets'))
Flight.buyTicket(one, qty)
print("Hello")
elif a == 4:
for Flight in FlightList:
print(Flight.flightNo)
re4 = input('Enter flight number to view seats: ')
for i in FlightList:
if i.flightNo == re4:
for a in range(len(i.seats)):
for b in range(len(i.seats[a])):
print(i.seats[a][b], end=" ")
print()
elif a == 5:
re4 = input('Enter flight number to view seats: ')
for i in FlightList:
if i.flightNo == re4:
i.totalSales()
elif a == 6:
re4 = input('Enter flight number to view seats: ')
for i in FlightList:
if i.flightNo == re4:
i.displayDetails()
elif a == 7:
for item in FlightList:
item.displayDetails()
elif a == 0:
sys.exit(0)
I need to be able to input a value for each seat and have the script print out the total for all seats when the user enters 'q' to quit. Here is the code so far:
cost = []
print 'Welcome to the receipt program!'
while True:
cost = raw_input("Enter the value for the seat ['q' to quit]: ")
if cost == 'q':
break
print '*****'
print 'Total: $', cost
totalCost = 0
print 'Welcome to the receipt program!'
while True:
cost = raw_input("Enter the value for the seat ['q' to quit]: ")
if cost == 'q':
break
else:
totalCost += int(cost)
print '*****'
print 'Total: $', totalCost