price = input("How much: ")
country = input("which country are you from :")
tax = 0
total = int(price) + (int(price)*(tax/100))
if country =="Canada" :
province = input("Which province? :")
if province == "Alberta" :
tax = 5
print(total)
elif province == "Ontario" :
tax = 13
print(total)
else :
tax = 11
print(total)
else :
tax = 0
print(total)
This code does not update the tax and doesn't calculate total afterward accordingly. Can anyone suggest any solution?
The issue is you are calculating total before changing tax to be the correct value. You can fix this by moving the calculation so that it happens after tax has been set.
price = input("How much: ")
country = input("which country are you from :")
tax = 0
if country == "Canada":
province = input("Which province? :")
if province == "Alberta":
tax = 5
elif province == "Ontario":
tax = 13
else:
tax = 11
else:
tax = 0
total = int(price) + (int(price)*(tax/100))
print(total)
Well, the problem is, you pre-calculated the total before the if statement with tax = 0. That would always return the same value.
Try calculating the total everytime you update the tax.
Something like this:
tax = 5
total = int(price) + (int(price)*(tax/100))
print(total)
Have a look at this simple example. I think it can help you "rethink" your data-sctructure. Good luck!
taxes = {
'Canada': {
'Alberta': 5,
'Ontario': 13,
'default': 11
}
}
def taxfunc(price, tax):
return price + price*tax/100
price = int(input("How much: "))
country = input("which country are you from :").title()
if country in taxes:
province = input("Which province? :").title()
tax = taxfunc(price, taxes[country].get(province, taxes[country]['default']))
print('Your tax is: {}'.format(tax))
else:
print('no data')
Try this: After getting the tax, then calculate the total. Problem of your code is you calculate the total before assigning values to tax. Always your total is for tax = 0 only. But moving the total calculation to the bottom will fix the issue.
price = input("How much: ")
country = input("which country are you from :")
tax = 0
if country =="Canada" :
province = input("Which province? :")
if province == "Alberta" :
tax = 5
elif province == "Ontario" :
tax = 13
else :
tax = 11
else :
tax = 0
total = int(price) + (int(price)*(tax/100))
print(total)
Related
I am currently working on improving my commission program by implementing arrays into my program. However, I cannot properly display my commission results anymore. If I revert some array changes, I can display my commission fine. Where did I do wrong? I would appreciate any feedback on my code posted below. I'm a beginner and have included code that I have learned up to this point.
MAX = 10
def main():
comp_name = [""] * MAX
sales_amount = [0.0] * MAX
total_sales_amount = 0.0
commission = 0.0
bonus = 0.0
more_sales = 'Y'
select_item = 0
welcome_message()
while more_sales == 'Y':
comp_name[select_item] = get_comp_name()
sales_amount[select_item] = get_sales_amount()
total_sales_amount = total_sales_amount + (sales_amount[select_item] + sales_amount[select_item])
more_sales = more_sales_input()
select_item = select_item + 1
commission += get_commission_calc(sales_amount[select_item])
print_receipt(comp_name, sales_amount, commission, select_item)
bonus = get_bonus(commission)
commission = commission + bonus
print_totals(bonus, commission)
def print_receipt(comp_name, sales_amount, total_commission, select_item):
sub_total = 0
count = 0
print("\nCompany Name Sales Your Commission")
print("------------ ----- ---------------")
while count < select_item:
print("{0:<15}".format(comp_name[count]), "\t\t$ ", format(sales_amount[count], ".2f"), "\t$ ", format(sales_amount[count], ".2f"))
sub_total = sub_total + (sales_amount[count])
count = count + 1
print("-----------------------------------------------")
print("Collect: $", format(total_commission, ".2f"))
def get_comp_name():
comp = ""
comp = input("\nEnter Company name: ")
return comp
def more_sales_input():
more = ""
more = input("Do you have more sales to add? (y/n): ")
more = more.upper()
while more != "Y" and more!= "N":
print("Invalid entry, either y or n.")
more = input("Do you have more sales to add? (y/n): ")
more = more.upper()
return more
def get_sales_amount():
sales = 0.0
while True:
try:
sales = float(input("Please enter sales $ "))
if sales < 0:
print("Invalid, must be a positive numeric!")
else:
return sales
except:
print("Invalid, must be a positive numeric!")
def get_commission_calc(sales):
commission = 0.0
if sales >= 20000:
commission = sales * .10
elif sales >= 10000:
commission = sales * .07
else:
commission = sales * .05
return commission
def get_bonus(commission):
if commission >= 1000:
return + 500
else:
return 0
def print_totals(bonus, total_commission):
if bonus > 0:
print("\nYou earned a $500 bonus added to your pay!")
else:
print("\nYou did not yet meet requirements for a bonus!")
print("\nYour commission is", '${:,.2f}'.format(total_commission))
main()
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
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:
I have a piece of python code that is supposed to end if a variable is equal to the string 'x', but it doesnt, I dont understand why. Can someone explain please
counter = 0
total_price = 0
biggest_price = 0
smallest_price = 10000000000
house_type = 0
while house_type != "x":
house_type = input("What is the house type? ")
if house_type != "x":
number_of_rooms = int(input("How many rooms does the house have? "))
age = int(input("How old is the house? "))
price = int(input("What is the houses price? "))
if price > biggest_price :
biggest_house_type = house_type
biggest_rooms = number_of_rooms
biggest_age = age
biggest_price = price
if price < smallest_price :
smallest_house_type = house_type
smallest_rooms = number_of_rooms
smallest_age = age
smallest_house_price = price
total_price = total_price + price
counter = counter + 1
print(biggest_house_type, biggest_rooms, biggest_age, biggest_price)
print(smallest_house_price, smallest_rooms, smallest_age, smallest_price)
print(total_price / counter)
Can someone explain why the program doesn't end when X is pressed, and instead just gives house_type the value of 'x'
There were a number of issues. I tried to make a minimal working example.
counter = 0
total_price = 0
biggest_price = 0
smallest_price = 10000000000
house_type = ''
while house_type != "x":
house_type = raw_input("What is the house type? ")
if house_type != "x":
number_of_rooms = int(raw_input("How many rooms does the house have? "))
age = int(raw_input("How old is the house? "))
price = int(raw_input("What is the houses price? "))
if price > biggest_price :
biggest_price = price
if price < smallest_price :
smallest_price = price
total_price = total_price + price
counter = counter + 1
print(biggest_price)
print(smallest_price)
print(total_price / counter)
Output:
What is the house type? 3
How many rooms does the house have? 5
How old is the house? 30
What is the houses price? 100000
100000
100000
100000
What is the house type? 4
How many rooms does the house have? 2
How old is the house? 10
What is the houses price? 200000
200000
100000
150000
What is the house type? x
NOTE:
If you are on Python 2.x use raw_input(). If you are on Python 3.x use input()
For my code below in python. How do I make it so if the country is not canada then just have it print the total_price with no tax? Right now if I put USA it gives me the right price but it also gives me the price for the other provinces not mentioned.
country = raw_input('What country are you from? ').lower()
if country == 'canada':
total_price = int(raw_input('What was your total price? '))
province = raw_input('What province are you from? ').lower()
elif country != 'canada':
total_price = int(raw_input('What was your total price? '))
if province == 'alberta':
total_alberta = (total_price * .00005) + total_price
print 'Your total price is ' + str(total_alberta)
if province == 'ontario' or province == 'new brunswick'\
or province == 'nova scotia':
total_onn = (total_price * .0013) + total_price
print 'Your total price is ' + str(total_onn)
if country == 'canada' and province != 'ontario' and province != 'new brunswick' and province != 'nova scotia' and province != 'alberta':
total_else = ((total_price * .0006) + (total_price * .0005)) \
+ total_price
print 'Your total price is ' + str(total_else)
else:
print 'Your total price is ' + str(total_price)
clean and pythonic version - your logic and ifs were poorly nested:
base_canada_tax = 0.13
provinces = {'alberta': 0.05, 'ontario': base_canada_tax, 'new brunswick': base_canada_tax, 'nova scotia': base_canada_tax}
country = raw_input('What country are you from? ').lower()
total_price = int(raw_input('What was your total price? '))
if country == 'canada':
province_in = raw_input('What province are you from? ').lower()
total_price *= 1 + provinces.get(province_in, base_canada_tax)
print 'Your total price is {0}'.format(total_price)
Put the code in the first if :
country = raw_input('What country are you from? ').lower()
if country == 'canada':
total_price = int(raw_input('What was your total price? '))
province = raw_input('What province are you from? ').lower()
if province == 'alberta':
total_alberta = (total_price * .00005) + total_price
print 'Your total price is ' + str(total_alberta)
elif province == 'ontario' or province == 'new brunswick'\
or province == 'nova scotia':
total_onn = (total_price * .0013) + total_price
print 'Your total price is ' + str(total_onn)
else:
total_else = ((total_price * .0006) + (total_price * .0005)) \
+ total_price
print 'Your total price is ' + str(total_else)
else:
total_price = int(raw_input('What was your total price? '))
print 'Your total price is ' + str(total_price)
Nest the province logic into the if country == "canada"
country = raw_input('What country are you from? ').lower()
total_price = int(raw_input('What was your total price? '))
if country == 'canada':
province = raw_input('What province are you from? ').lower()
if province == 'alberta':
total_price= (total_price * .00005) + total_price
elif province in ['ontario', 'new brunswick', 'nova scotia']:
total_price= (total_price * .0013) + total_price
print 'Your total price is ' + str(total_price)
Your boolean logic was also redundant in many cases and could be trimmed as I did above
put your if province statment inside the if canada then put if the country is not Canada it will jump outside the whole if statment
if country =='canada':
if province =='ontario':
.....
else //the not canada statment
This is based on #Incognos's answer, with the logic and numbers corrected:
provinces = {'alberta': 1.05, 'ontario': 1.13,
'new brunswick': 1.13, 'nova scotia': 1.13} # excess alberta removed
base_canada_tax = 1.113 # 6% and 5% together as per question's (corrected) code
country = raw_input('What country are you from? ').lower()
total_price = float(raw_input('What was your total price? ')) # float
if country == 'canada':
province = raw_input('What province are you from? ').lower()
total_price *= provinces.get(province, base_canada_tax)
print 'Your total price is', total_price