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
Related
I'm building a basic program to calculate taxes in the UK. The code looks like this:
income = int(input("Income: "))
taxable = income - 12570
if income < 12_571:
print(f"You pay no tax.
Your income is £{income:.2f}")
elif income < 50_271:
afterTax = taxable * 0.8
realIncome = afterTax + 12570
print(f"You pay 20% tax.
Your income is £{realIncome:.2f}")
elif income < 150_000:
afterTax = taxable * 0.6
realIncome = afterTax + 12570
print(f"You pay 40% tax.
Your income is £{realIncome:.2f}")
else:
afterTax = taxable * 0.55
realIncome = afterTax + 12570
print(f"You pay 45% tax.
Your income is £{realIncome:.2f}")
`
When I run it, I get this:
Income: 3555555555555555532 You pay 45% tax. Your income is £1955555555555561472.00
The problem is I either format it to have 2 decimal places with :.2f, or to have comas with :,. Is there a way to do both?
this is the code
wallet = int(input("wallet = "))
price = 100
print("price = " + str(price))
while price <= 1000:
if wallet >= price:
ask = input('would you like to purchase again? (y/n)')
if ask.upper() == "Y":
left = int(wallet) - price
wallet = left
print("you now have " + str(left) + " left")
elif ask.upper() == "N":
print("transaction cancelled")
else:
print("invalid reply")
left = wallet
price += 100
print('new price = ' + str(price))
else:
print("you do not have enough money to purchase more")
exit()
and this is the output
wallet = 1000
price = 100
would you like to purchase again? (y/n)y
you now have 900 left
new price = 200
would you like to purchase again? (y/n)y
you now have 700 left
new price = 300
would you like to purchase again? (y/n)y
you now have 400 left
new price = 400
would you like to purchase again? (y/n)y
you now have 0 left
new price = 500
new price = 600
new price = 700
new price = 800
new price = 900
new price = 1000
new price = 1100
you do not have enough money to purchase more
Process finished with exit code 0
i am making a continous purchase command where everytime a purchase is made, the price increase by 100, until no more money is left in customer's wallet. after which it should end but it first keeps incresing price for some time then stops.
You should stop when you have not enough money
while wallet >= price:
Also here's a better code, with removed useless conversion to int/str, and useless left that is always equals to wallet when used
wallet = int(input("wallet = "))
price = 100
print("price =", price)
while and wallet >= price:
ask = input('would you like to purchase again? (y/n)').upper()
if ask == "Y":
wallet -= price
print("you now have", wallet, "left")
elif ask == "N":
print("transaction cancelled")
else:
print("invalid reply")
price += 100
print('new price =', price)
else:
print("you do not have enough money to purchase more")
exit()
I am trying to make a Shipping calculator in python by using IF Statements.
The application should calculate the total cost of an order including shipping. I am stuck at a point where python just won't run my code at all. I have a feeling I'm close but I do not know what is wrong with what I'm inputting because python won't return any errors. please someone just steer me in the right direction.
Instructions:
Create a program that calculates the total cost of an order including shipping.
When your program is run it should ...
Print the name of the program "Shipping Calculator"
Prompt the user to type in the Cost of Items Ordered
If the user enters a number that’s less than zero, display an error message and give the user a chance to enter the number again.
(note: if you know loops/iterations, OK to use here, but if not, just a simple one-time check with an if statement will be OK here.)
For example: if the cost is less than zero, print an error message and then re-ask once for the input.
Use the following table to calculate shipping cost:
Cost of Items
Shipping cost
<30
5.95
30.00-49.99
7.95
50.00-74.99
9.95
>75.00
FREE
Print the Shipping cost and Total Cost to ship the item
End the program with an exit greeting of your choice (e.g. Thank you for using our shipping calculator!)
Example 1:
=================
Shipping Calculator
=================
Cost of items ordered: 49.99
Shipping cost: 7.95
Total cost: 57.94
Thank you for using our shipping calculator!
Example 2:
=================
Shipping Calculator
=================
Cost of items ordered: -65.50
You must enter a positive number. Please try again.
Cost of items ordered: 65.50
Shipping cost: 9.95
Total cost: 75.45
Thank you for using our shipping calculator!
Here is the code I have written out so far:
#Assignment shipping calculator
#Author: Name
def main():
print("Shipping Calculator")
subtotal = calc_subtotal()
shipping = calc_shipping()
total = calc_total()
main()
def calc_subtotal():
subtotal = float(input("Cost of Items Ordered: $"))
if subtotal <= 0:
print("You must enter a positive number. Please try again.")
return subtotal
def calc_shipping():
subtotal = calc_subtotal()
shipping = calc_shipping
if subtotal >= 1 and subtotal <= 29.99:
shipping = 5.95
print("Shipping Cost: $5.95")
if subtotal >= 30 and subtotal <= 49.99:
shipping = 7.95
print("Shipping Cost: $7.95")
if subtotal >= 50 and subtotal <= 74.99:
shipping = 9.95
print("Shipping Cost: $9.95")
if subtotal >= 75:
shipping = 0
print("Shipping Cost: Free")
def calc_total():
total = calc_subtotal() + calc_shipping()
print("Total Cost: ",total)
print("Thank you for using our shipping calculator!")
First, I will put the code here then explain all the changes I made (your original attempt was very close, just a few tweaks):
#Assignment shipping calculator
#Author: Name
def main():
print("Shipping Calculator")
subtotal = calc_subtotal()
shipping = calc_shipping(subtotal)
calc_total(subtotal,shipping)
def calc_subtotal():
subtotal = float(input("Cost of Items Ordered: $"))
while subtotal <= 0:
print("You must enter a positive number. Please try again.")
subtotal = float(input("Cost of Items Ordered: $"))
return subtotal
def calc_shipping(subtotal):
if subtotal >= 1 and subtotal <= 29.99:
shipping = 5.95
print("Shipping Cost: $5.95")
if subtotal >= 30 and subtotal <= 49.99:
shipping = 7.95
print("Shipping Cost: $7.95")
if subtotal >= 50 and subtotal <= 74.99:
shipping = 9.95
print("Shipping Cost: $9.95")
if subtotal >= 75:
shipping = 0
print("Shipping Cost: Free")
return shipping
def calc_total(subtotal,shipping):
total = subtotal + shipping
print("Total Cost: $" + str(round(total,2)))
print("Thank you for using our shipping calculator!")
main()
As #Devang Sanghani mentioned, you should call your main() outside of your function so that it will run
For your calc_subtotal() function, use a while loop to keep taking in user input until given a valid number. Make sure you move your return subtotal outside of this loop so that it will only return it once this number is valid.
In your calc_shipping() function, make sure you take in subtotal as a parameter since you are using it in your function. Make sure you also return shipping.
Similarly, in your calc_total() function, take in both subtotal and shipping as parameters since they are used in your function.
Given these changes, update your main() function accordingly.
I hope these changes made sense! Please let me know if you need any further help or clarification :)
Adding to the above answers, also consider the case where the price can be a few cents, so this line should change:
if subtotal >= 0 and subtotal <= 29.99: # changed from 1 to 0
So there seem to be 2 errors:
You forgot to call the main function
You indented the return statement in calc_subtotal() so it returns the value only if the subtotal <= 0
The correct code might be:
def main():
print("Shipping Calculator")
subtotal = calc_subtotal()
shipping = calc_shipping()
total = calc_total()
def calc_subtotal():
subtotal = float(input("Cost of Items Ordered: $"))
if subtotal <= 0:
print("You must enter a positive number. Please try again.")
calc_subtotal() # Re asking for the input in case of invalid input
else:
return subtotal # returning subtotal in case of valid input
def calc_shipping():
subtotal = calc_subtotal()
shipping = calc_shipping
if subtotal >= 0 and subtotal <= 29.99:
shipping = 5.95
print("Shipping Cost: $5.95")
if subtotal >= 30 and subtotal <= 49.99:
shipping = 7.95
print("Shipping Cost: $7.95")
if subtotal >= 50 and subtotal <= 74.99:
shipping = 9.95
print("Shipping Cost: $9.95")
if subtotal >= 75:
shipping = 0
print("Shipping Cost: Free")
def calc_total():
total = calc_subtotal() + calc_shipping()
print("Total Cost: ",total)
print("Thank you for using our shipping calculator!")
main() # Calling main
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)")
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: