I am trying to create a program that inputs the price and tax rate and returns the item number, price, tax rate, and item price in an orderly format.
Here is the criteria:
The user can enter multiple items until the user says otherwise.
It calculates and display the total amount of purchased items on the bottom.
The price gets a 3% discount if the total amount is 1000 or more
I am not allowed to use arrays to solve this problem and I must separate the inputs from the outputs on the screen.
An example output is shown here:
Enter the price: 245.78
Enter the tax rate: 12
Are there any more items? (y/n) y
Enter the price: 34
Enter the tax rate: 10
Are there any more items? (y/n) y
Enter the price: 105.45
Enter the tax rate: 7
Are there any more items? (y/n) n
Item Price Tax Rate % Item Price
====================================
1 245.78 12% 275.27
2 34.00 10% 37.40
3 105.45 7% 112.83
Total amount: $425.51
Here is my code so far:
price= float(input('Enter the price: '))
taxRate= float(input('Enter the tax rate: '))
itemPrice = price * (1 + taxRate/100)
acc= 0
while True:
query=input('Are there any more items? (y/n)')
if query== 'y':
price= float(input('Enter the price: '))
taxRate= float(input('Enter the tax rate: '))
itemPrice = price * (1 + taxRate/100)
print(itemPrice )
acc+=1
elif query=='n':
break
print ("Item Price Tax Rate% Item Price")
print ("=========================================")
print( (acc+1) , format(price,'10.2f'), format(taxRate,'10.2f') ,
format(itemPrice,'14.2f') )
for num in range(0,acc):
print (acc, price, taxRate, itemPrice)
The output is shown as this:
Enter the price: 245.78
Enter the tax rate: 12
Are there any more items? (y/n)y
Enter the price: 34
Enter the tax rate: 10
37.400000000000006
Are there any more items? (y/n)y
Enter the price: 105.45
Enter the tax rate: 7
112.8315
Are there any more items? (y/n)n
Item Price Tax Rate% Item Price
=========================================
3 105.45 7.00 112.83
2 105.45 7.0 112.8315
2 105.45 7.0 112.8315
I just have a hard time trying to do this without using an array.. can anyone be of assistance?
You could build a string as a buffer for the output?
Like this:
out = ""
acc = 0
totalAmount = 0
query = 'y'
while query == 'y':
price = float(input('Enter the price: '))
taxRate = float(input('Enter the tax rate: '))
itemPrice = price * (1 + taxRate/100)
acc += 1
totalAmount += itemPrice
out += f"{acc:>4} {price:9.2f} {taxRate:11.2f}% {itemPrice:13.2f}\n"
query = input('Are there any more items? (y/n) ')
print("Item Price Tax Rate% Item Price")
print("=========================================")
print(out)
print(f"Total amount: ${totalAmount:.2f}")
if totalAmount >= 1000:
print(" Discount: 3%")
print(f"Total amount: ${totalAmount*0.97:.2f} (after discount)")
Related
The following code is a program for an assignment last week. The assignment was to create a program that you would enter information into as a cashier and it would total everything up for you based on the information entered. Part of this week's assignment is to enhance it so multiple items can be handled by the program, using a while loop. This improved program should output the total for all items.
This is an example of the output the professor is looking for.
Original ticket price: $100
Is this item reduced?y
Is this item taxable?y
Here is your bill
Orginal Price $100.00
Reduced Price $25.00
Final Price $75.00
7% Sales Tax $5.25
Total amount due $80.25
Original ticket price: $75
Is this item reduced?y
Is this item taxable?n
Here is your bill
Orginal Price $75.00
Reduced Price $18.75
Final Price $56.25
7% Sales Tax $0.00
Total amount due $56.25
Total amount due is $136.50
# Enter constants for sale & salesTax
SALE = .25
SALES_TAX = .07
# Enter the ticket price of the item
origPrice = float(input('Original ticket price or 0 to quit: $'))
# Is the item reduced? Y/y or N/n - use if/elif to determine salePrice
reduced = input('Is this item reduced?')
if reduced == 'Y' or reduced == 'y':
salePrice = origPrice * SALE
elif reduced == 'N' or reduced == 'n':
salePrice = 0.00
# Enter constant for finalPrice = origPrice - salePrice
finalPrice = origPrice - salePrice
# Is the item taxable? Y/y or N/n - use if/elif to determine tax
taxable = input('Is this item taxable?')
if taxable == 'Y' or taxable == 'y':
tax = finalPrice * SALES_TAX
elif taxable == 'N' or taxable == 'n':
tax = 0.00
# Enter all Print Statements
print('Here is your bill')
print('Orginal Price $', format(origPrice, ',.2f'),sep='')
print('Reduced Price $', format(salePrice, ',.2f'),sep='')
print('Final Price $', format(finalPrice, ',.2f'),sep='')
print('7% Sales Tax $', format(tax, ',.2f'),sep='')
print('Total amount due $', format(finalPrice + tax, ',.2f'),sep='')
Always nice to see people learn programming. Python is a great Lang and there's plenty of resources out there. Having said that, checkout the code below and if your interested seeing it run click the link below. Its' a Google Colab note book, it's pretty much a python env to develop from your browser.
# Enter constants for sale & salesTax
SALE = .25
SALES_TAX = .07
Order = []
while True:
# Enter the ticket price of the item
tmp = float(input('Original ticket price or 0 to quit: $'))
if 0 == tmp:
break
else:
origPrice = tmp
# Is the item reduced? Y/y or N/n - use if/elif to determine salePrice
reduced = input('Is this item reduced?')
if reduced == 'Y' or reduced == 'y':
salePrice = origPrice * SALE
elif reduced == 'N' or reduced == 'n':
salePrice = 0.00
# Enter constant for finalPrice = origPrice - salePrice
finalPrice = origPrice - salePrice
# Is the item taxable? Y/y or N/n - use if/elif to determine tax
taxable = input('Is this item taxable?')
if taxable == 'Y' or taxable == 'y':
tax = finalPrice * SALES_TAX
elif taxable == 'N' or taxable == 'n':
tax = 0.00
result = (finalPrice + tax)
Order.append(['Orginal Price ${0} '.format(origPrice, '.2f'), 'Reduced Price ${0} '.format(salePrice, '.2f'), 'Final Price ${0} '.format(finalPrice, '.2f'),
'7% Sales Tax ${0} '.format(tax, '.2f'), 'Total amount due ${0} '.format(result, '.2f')])
# Enter all Print Statements
print('\n')
for i in Order:
print(i[0])
print(i[1])
print(i[2])
print(i[3])
print(i[4])
Link Colab: https://colab.research.google.com/drive/1S64fGVM1rQTv05rJBlvjOVrwHQFm8faK?usp=sharing
Senario One:
Welcome to StackOverflow! From the sample output that your professor gave you, it seems like you'll need to wrap your current code (excluding constant declarations) in a while True loop with the break condition, but also add another variable called totalAmountDue. This variable will be changed every time a new item is added. If you were to apply the changes, it should look like this:
# Enter constants for sale & salesTax
SALE = .25
SALES_TAX = .07
# Counter for the total amount of money from all items, this includes tax as well
totalAmountDue = 0
while True:
# Enter the ticket price of the item
origPrice = float(input('Original ticket price or 0 to quit: $'))
# Breaks out of the loop once the user wants to quit
if (origPrice == 0):
break
# Is the item reduced? Y/y or N/n - use if/elif to determine salePrice
reduced = input('Is this item reduced?')
if reduced == 'Y' or reduced == 'y':
salePrice = origPrice * SALE
elif reduced == 'N' or reduced == 'n':
salePrice = 0.00
# Enter constant for finalPrice = origPrice - salePrice
finalPrice = origPrice - salePrice
# Is the item taxable? Y/y or N/n - use if/elif to determine tax
taxable = input('Is this item taxable?')
if taxable == 'Y' or taxable == 'y':
tax = finalPrice * SALES_TAX
elif taxable == 'N' or taxable == 'n':
tax = 0.00
# Adds the final price of this product to the total price of all items
totalAmountDue += finalPrice + tax
# Enter all Print Statements
print("Here's the breakdown for this item: ")
print('Orginal Price $', format(origPrice, ',.2f'),sep='')
print('Reduced Price $', format(salePrice, ',.2f'),sep='')
print('Final Price $', format(finalPrice, ',.2f'),sep='')
print('7% Sales Tax $', format(tax, ',.2f'),sep='')
print('Total amount due $', format(finalPrice + tax, ',.2f'), "\n",sep='')
print("\nTotal amount due for all items: $", format(totalAmountDue, ',.2f'))
This is the output of the edited version:
Original ticket price or 0 to quit: $10
Is this item reduced?n
Is this item taxable?y
Here's the breakdown for this item:
Orginal Price $10.00
Reduced Price $0.00
Final Price $10.00
7% Sales Tax $0.70
Total amount due $10.70
Original ticket price or 0 to quit: $23123123123
Is this item reduced?n
Is this item taxable?y
Here's the breakdown for this item:
Orginal Price $23,123,123,123.00
Reduced Price $0.00
Final Price $23,123,123,123.00
7% Sales Tax $1,618,618,618.61
Total amount due $24,741,741,741.61
Original ticket price or 0 to quit: $0
Total amount due for all items: $ 24,741,741,752.31
If you'd like to learn more about while loops in python, you can check out this link: https://www.w3schools.com/python/python_while_loops.asp
income=float(input("enter the annual income: ")
if income<85528:
tax=(income-556.02)*0.18
else:
tax=(income-85528)*0.32+14839.02
tax=round(tax,0)
print("the tax is: ", tax, "thalers")
Why does it keep giving an error on line 2?
You have a lacking parenthesis in the 1st line: ")". It can be fixed by:
income = float(input("enter the annual income: "))
Complete program:
income = float(input("enter the annual income: "))
if income < 85528:
tax = (income - 556.02) * 0.18
else:
tax = (income - 85528) * 0.32 + 14839.02
tax = round(tax, 0)
print("the tax is: ", tax, "thalers")
Returns:
enter the annual income: 435
the tax is: -22.0 thalers
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
i'm a foundation year student at University so I am very new to coding. I'm struggling with this and am in need of some help, this is the question and code I have currently written:
"Write a python program to simulate an online store.
The program should begin by displaying a list of products and their prices. There should be a minimum of 4 products offered. The program should ask the user to choose a product and then ask the user to enter the quantity they require of that product. The program should then allow the user to keep choosing more products and quantities until they enter something to indicate they want to end the program (e.g. a given number or ‘q’ or ‘exit’). The program should then tell the user the total amount for the products they have selected. "
shopping_basket = {}
print("Welcome to the online drink store!\nThese are the drinks we offer\n1. Lemonade: £1.50\n2.
Coke: £2.00\n3. Fanta £1.00\n4. Water: £0.50")
Price = {"Lemonade": 1.50, "Coke": 2.00, "Fanta": 1.00, "Water": 0.50 }
option = int(input("Which drink would you like to purchase?: "))
while option!= 0:
if option == 1:
qnty = int(input("Enter the quantity: "))
total = qnty * 1.50
print("The price is: " + str(total))
elif option == 2:
qnty = int(input("Enter the quantity: "))
total = qnty * 2.00
print("The price is: " + str(total))
elif option == 3:
qnty = int(input("Enter the quantity: "))
total = qnty * 1.00
print("The price is: " + str(total))
elif option == 4:
qnty = int(input("Enter the quantity: "))
total = qnty * 0.50
print("The price is: " + str(total))
print("Would you like another item? enter Yes or No:")
else:
print("The total price of your basket is: " , total = Price * qnty)
This is the code I have tried, but after it stating the price it just constantly asks for the quantity.
I didn't want to post a new answer but instead make a comment, but alas, not enough reputation.
I just wanted to add to Daemon Painter's answer and say that the final total bill also isn't working as it is multiplying a dict by an int.
What could work is to initialize out of the loop the total variable as well a new total_cost variable, and place:
total_cost += total
Inside the while loop but outside the if conditions.
That way the last line can just be:
print("The total price of your basket is: ", total_cost)
Edit: the code, working as intended:
price = {"Lemonade": 1.50, "Coke": 2.00, "Fanta": 1.00, "Water": 0.50}
shopping_basket = {}
print("Welcome to the online drink store!\nThese are the drinks we offer\n1. Lemonade: £1.50\n2. Coke: £2.00\n3. Fanta £1.00\n4. Water: £0.50")
buy_another_flag = 1
total_cost, total = 0, 0
while buy_another_flag != 0:
option = int(input("Which drink would you like to purchase?: "))
if option == 1:
qnty = int(input("Enter the quantity: "))
total = qnty * 1.50
print("The price is: " + str(total))
elif option == 2:
qnty = int(input("Enter the quantity: "))
total = qnty * 2.00
print("The price is: " + str(total))
elif option == 3:
qnty = int(input("Enter the quantity: "))
total = qnty * 1.00
print("The price is: " + str(total))
elif option == 4:
qnty = int(input("Enter the quantity: "))
total = qnty * 0.50
print("The price is: " + str(total))
total_cost += total
buy_another_flag = int(input("Would you like another item? enter Yes (1) or No (0):"))
print("The total price of your basket is: ", total_cost)
You are looping indefinitely in the while loop.
Once you assigned option via User input here:
option = int(input("Which drink would you like to purchase?: "))
this condition is always fulfilled:
while option!= 0:
Here, you should not just print, but re-assign the option:
print("Would you like another item? enter Yes or No:")
something like this:
option = int(input("Would you like another item? enter Yes or No:"))
I hope this is pointing you in the right direction :)
(I've made assumptions on how you should have the code formatted in your original script. They might be wrong...)
I need to request 3 items from a user then,
Request the price of those three items from a user
Calculate the total of all three
Calculate the average
print a statement saying "the total of product 1, product 2, product 3 is xxxx and the average is xxxx
I've tried to use 6 strings (so 3 for the products and 3 for the prices) so I could call each value separately. But then I was told an array would greatly shorten the code and neaten it up so I tried that but I'm battling to call it forward. I know how to work out the average and total but I'm struggling with the array part.
products = []
products = input("Please enter three shopping products: ")
The code then prints and allows me to input the 3 products like below:
Please enter three shopping products: Shampoo, Soap, Bread
(I still need to ask the prices for each product through an array)
shopping = products[0]
print(shopping)
S
The first way I tried was the 6 strings, like below:
product1 = input("Please enter a shopping item: ")
product2 = input("Please enter a second shopping item: ")
product3 = input("Please enter a third shopping item: ")
price1 = input("Please enter the price for the first shopping item: ")
price2 = input("Please enter the price for the second shopping item: ")
price3 = input("Please enter the price for the third shopping item: ")
It prints the question and allows my input, but it doesn't look very neat.
I now need to calculate the average of the prices as well as the total (which I can do without the array but if I'm using the array it's confusing)
I'm wanting my end result to be:
The Total of [product1], [product2], [product3] is Rxx, xx and the average price of the items are Rxx, xx.
products = []
prices = []
for i in range (0,3):
product = raw_input("Enter your Item to the List: ")
products.append(product)
for j in range (0,3):
price = float(raw_input("Enter your price to the List: "))
prices.append(price)
print "The total of products is " + str(sum(prices)) + " and the average price is " + str(sum(prices)/3)
You could split the input into an array which would shorten the code by quite a bit.
products = input("Please enter three shopping products (Seperated by comma): ")
result = [x.strip() for x in products.split(',')]
This would strip the string of spaces and but them into an array.
class ShoppingItem:
price = 0
name = ""
def __init__(self, name, price):
self.price = price
self.name = name
shoppingItems = []
for i in range(0, 3):
productName = input("Please enter a shopping item: ")
price = input("Please enter a price for the shopping item: ")
shoppingItems.append(ShoppingItem(productName, price))
total = sum(i.price for i in shoppingItems)
average = total/len(shoppingItems))
itemsList = []
priceList = []
for i in range(1,4):
itemStr = "Enter the {} shopping item: ".format(i)
itemsList.append(input(itemStr))
priceStr = "Enter the price of {} shopping item: ".format(itemsList[i-1])
priceList.append(int(input(priceStr)))
print("The Total of {}, {}, {} is {} and the average price of the items are {}".format(*itemsList, sum(priceList), sum(priceList) / float(len(priceList))))
OUTPUT:
Enter the 1 shopping item: shopping_item_1
Enter the price of shopping_item_1: 1
Enter the 2 shopping item: shopping_item_2
Enter the price of shopping_item_2: 2
Enter the 3 shopping item: shopping_item_3
Enter the price of shopping_item_3: 3
The Total of shopping_item_1, shopping_item_2, shopping_item_3 is 6 and the average price of the items are 2.0
EDIT:
If the shopping items are unique, I'd suggest a dict approach with items as keys and prices as values:
n = int(input("Enter the total items: "))
shoppingDict = {}
for i in range(n):
keys = input("Enter the shopping item: ")
values = int(input("Enter the price of item: "))
shoppingDict[keys] = values
print("The Total of {}, {}, {} is {} and the average price of the items are {}".format(*shoppingDict.keys(), sum(shoppingDict.values()), sum(shoppingDict.values()) / float(sum(shoppingDict.values()))))
OUTPUT:
Enter the total items: 3
Enter the shopping item: shopping_item_1
Enter the price of item: 1
Enter the shopping item: shopping_item_2
Enter the price of item: 2
Enter the shopping item: shopping_item_3
Enter the price of item: 3
The Total of shopping_item_1, shopping_item_2, shopping_item_3 is 6 and the average price of the items are 1.0
I am writing a code in python where I use different functions to calculate wage, federal tax, state tax, and net worth. Everything is fine except my output says, ('Your wage is: $', 989) instead of Your wage is: $989 I tried using +(wag) but it doesn't let me run it. How do I get rid of the parenthesis, comma, and quotation marks from the output? And how do I make the output have no decimal points? I am not using float, so I don't know why it's still giving me decimal points. Here's my code:
def Calculatewages():
wage = (work*hours)
return wage
def CalcualteFederaltax():
if (status== ("Married")):
federaltax = 0.20
elif (status== ("Single")):
federaltax = 0.25
elif status:
federaltax = 0.22
federaltax = float(wag*federaltax)
return federaltax
def Calculatestatetax():
if(state=="CA") or (state=="NV") or (state=="SD") or (state=="WA") or (state=="AZ"):
statetax = 0.08
if (state== "TX") or(state=="IL") or (state=="MO") or (state=="OH") or (state=="VA"):
statetax = 0.07
if (state== "NM") or (state== "OR") or (state=="IN"):
statetax = 0.06
if (state):
statetax = 0.05
statetax = float(wag*statetax)
return statetax
def Calculatenet():
net = float(wag-FederalTax-StateTax)
return net
hours = input("Please enter your work hours: ")
work = input("Please enter your hourly rate: ")
state = input("Please enter your state of resident: ")
status = input("Please enter your marital status: ")
print("**********")
wag = Calculatewages()
FederalTax = CalcualteFederaltax()
StateTax = Calculatestatetax()
Net = Calculatenet()
print("Your wage is: $" ,wag)
print("Your federal tax is: $",FederalTax)
print("Your state tax is: $",StateTax)
print("Your net wage is: $",Net)
For this part:
print("Your wage is: $" ,wag)
print("Your federal tax is: $",FederalTax)
print("Your state tax is: $",StateTax)
print("Your net wage is: $",Net)
you can rewrite it as this using string's format() method:
print("Your wage is: ${}".format(wag))
print("Your federal tax is: ${}".format(FederalTax))
print("Your state tax is: ${}".format(StateTax))
print("Your net wage is: ${}".format(Net))
This is useful as you can insert the value into any place in the string (wherever you put the curly brackets).
As for your decimal points problem you can use the built in round function like this:
round(float(variable), int(decimal_places))
for example:
round(1.43523556, 2)
will return 1.44
There are no quotes or parenthesis in the output in python 3.x, Check if you are running on python 2 or python 3. Looks like you are on python 2 by judging your output.
So change all your print statements like this
print "Your net wage is: $", wag # remove brackets
...
However, if you want it to run on python 3 your code doesn't run as you are multiplying 2 strings in this line
def Calculatewages():
wage = (work*hours) # <------ here
return wage
To fix this issue you must cast them into int and then your code should run without problems.
hours = int(input("Please enter your work hours: ")) # < ---- Cast to int
work = int(input("Please enter your hourly rate: ")) # < ---- Cast to int
state = input("Please enter your state of resident: ")
status = input("Please enter your marital status: ")
My output:
Please enter your work hours: 8
Please enter your hourly rate: 10
Please enter your state of resident: IN
Please enter your marital status: Single
**********
Your wage is: $ 80
Your federal tax is: $ 20.0
Your state tax is: $ 4.0
Your net wage is: $ 56.0
you can also use string's format() method:
print("Your wage is: ${}".format(wag))
print("Your federal tax is: ${}".format(FederalTax))
print("Your state tax is: ${}".format(StateTax))
print("Your net wage is: ${}".format(Net))
If you're running under python3.x, then with your code, it should print out without the parenthesis, and if you're running under python2.x, then to get rid of the parenthesis, you might wanna try:
print "Your wage is: $", wag