I am learning Python and am trying to edit the code which has the following error:
If you enter a negative number, it will be added to the total and count. Modify the code so that negative numbers give an error message instead (but don’t end the loop) Hint: elif is your friend.
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)
# This `elif` block is the code I edited
elif price<0:
print('Error')
price= False
else:
moreItems = False
average = total / count
print('Total items:', count)
print('Total $', total)
print('Average price per item: $', average)
checkout()
How can I fix my code so it prints the "Error" message when a negative price is entered?
When the user submits a negative value to the price input, your code then runs if price != 0:.
To figure out what's going on more easily, I ran this code in the python shell:
>>> total = 0
>>> count = 0
>>> moreItems = True
>>> price = float(input('Enter price of item (0 when done): '))
Enter price of item (0 when done): -5
>>> price != 0
True
What you probably want instead is:
if price > 0:
...
elif price < 0:
print("Error")
You have to change this line:
if price != 0:
to this one:
if price > 0:
In if else or if elif statements, the code inside else or elif is only executed if the condition of if fails.
Ex:
if cond1:
code1
elif cond2:
code2
else:
code3
if cond1 is true then only code1 will run. If not cond2 will be checked, If True then only code2 will tun, hence the word "else" (elif is the same as else if)
In you question:
Modify the code so that negative numbers give an error message instead
(but don’t end the loop) Hint: elif is your friend.
In your code, If price is negative then price != 0 is True.
So because using elif, only this will run:
count = count + 1
total = total + price
print('Subtotal: $', total)
Code fix:
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)
elif price < 0:
print('Error')
price= False**
else:
moreItems = False
average = total / count
print('Total items:', count)
print('Total $', total)
print('Average price per item: $', average)
checkout()
Is this what you expected..? I have only done a few minor changes.
def checkout():
total = 0
count = 0
moreItems = True
while moreItems:
price = float(input('Enter price of item (0 when done): '))
if price > 0:
count += 1
total += price
print(f'Subtotal: $ {total}')
elif price < 0:
print('**Error**, Please enter a positive value')
else:
moreItems = False
average = total / count
print(f'Total items: {count}')
print(f'Total $ {total}')
print(f'Average price per item: $ {average}')
checkout()
Related
I need to create a program that will input a money amount in the form of a floating point number. The program will then calculate which dollars and coins to make this amount. Coins will be preferred in the least number of coins. If any of the values is zero, I need to not output the value. IE: if the change is 26 cents you only need to tell the user they will receive 1 quarter and 1 penny. No more, no less.
Below is what I have so far, the only thing I cant figure out is to make the program not output the zero values
# calculate amount of change needed
dollar = 100
quarter = 25
dime = 10
nickel = 5
penny = 1
def main():
calc = True
while calc:
lst = []
mon = ['dollars', 'quaters', 'dimes', 'nickels', 'pennys']
doll = 0
quart = 0
dimes = 0
nick = 0
pen = 0
total = int(float(input('Enter amount of change: '))*100)
amount = total
while amount - dollar >= 0:
amount -= dollar
doll += 1
while amount - quarter >= 0:
amount -= quarter
quart += 1
while amount - dime >= 0:
amount -= dime
dimes += 1
while amount - nickel >= 0:
amount -= nickel
nick += 1
while amount - penny >= 0:
amount -= penny
pen += 1
lst.append(doll)
lst.append(quart)
lst.append(dimes)
lst.append(nick)
lst.append(pen)
print('\nThe change owed is: ')
print(" ")
for i, e in zip(lst, mon):
print(i, e)
calc = input("\nPress 'Y' to try again or any other key to exit: ")
if calc != 'y' and calc != 'Y':
calc = False
if __name__ == "__main__":
main()
else:
pass
I ended up solving it
if doll >= 1:
lst.append(doll)
mon.append("dollars")
if quart >= 1:
lst.append(quart)
mon.append("quarters")
if dimes >= 1:
lst.append(dimes)
mon.append("dimes")
if nick >= 1:
lst.append("nickles")
if pen >= 1:
lst.append(pen)
mon.append("pennies")
this seems to have worked
Here is what ive done:
food =["cheeseburger", "smallchips", "drink"]
prices =[2.50, 1.50, 1]
x=0
myorderfood=[]
myordercost=[]
print("Burgers\n")
print("Menu:")
print("Cheeseburger. Cost - $2.50 each")
print("Small chips. Cost - $1.50 each")
print("Drink - Cola only. Cost - $1.00 each\n")
I want to display an invoice at the end once the user has completed there order showing there total price.
This is some of my code for just the drinks, same type of code used for cheeseburger etc. :
while True:
try:
drinkselect = input("Please select which drink:\n")
if drinkselect == "cola":
quantitydrink = int(input("How many would you like?\n"))
except ValueError:
print("Not valid")
continue
if drinkselect != "cola":
print("Not on our menu!\n")
else:
print("good choice\n")
break
You can use something like this:
from statistics import quantiles
from xml.etree.ElementPath import prepare_predicate
food =["cheeseburger", "smallchips", "drink"]
prices =[2.50, 1.50, 1]
x=0
price = 5
quantitydrink = 0
myorderfood=[]
myordercost=[]
print("Burgers\n")
print("Menu:")
print("Cheeseburger. Cost - $2.50 each")
print("Small chips. Cost - $1.50 each")
print("Drink - Cola only. Cost - $1.00 each\n")
print("10% GST applies to total amount (including both food and delivery)")
print("Delivery is free for food orders that are $30 or more")
print("Delivery cost is an additional $5 for food orders below $30\n")
while True:
try:
drinkselect = input("Please select which drink:\n")
if drinkselect == "cola":
quantitydrink += int(input("How many would you like?\n"))
except ValueError:
print("Not valid")
continue
if drinkselect != "cola":
print("Not on our menu!\n")
else:
print("good choice\n")
price += 1 * quantitydrink
print(f"Your total cost is {price}!")
break
So the base price is 5 for the delivery and if you pick cola it adds the price of the cola multiplied by the amount you purchase to the price variable.
The += operator is best for this.
Changes:
price = 5 #added this on line 8 because the delivery cost is 5 so that is the base price
quantitydrink = 0 #added this on line 9 so you can add the amount to it later in the code
quantitydrink += int(input("How many would you like?\n")) # changed this in line 26 to add the amount you are ordering to the initial value.
price += 1 * quantitydrink # added this in line 36 to calculate the price based on how many colas you are ordering and the base price
print(f"Your total cost is {price}!") #added this at line 37 to print the final price of the order
hope this helps!
FINAL CODE WITH ALL FIXES:
from statistics import quantiles
from xml.etree.ElementPath import prepare_predicate
finished = False
food =["cheeseburger", "smallchips", "drink", "delivery"]
prices =[2.50, 1.50, 1, 5]
x=0
price = 5
quantitydrink = 0
quantityburger = 0
quantitychips = 0
quantitydelivery = 0
myorderfood=[]
myordercost=[]
print("Burgers\n")
print("Menu:")
print("Cheeseburger. Cost - $2.50 each")
print("Small chips. Cost - $1.50 each")
print("Drink - Cola only. Cost - $1.00 each\n")
print("10% GST applies to total amount (including both food and delivery)")
print("Delivery is free for food orders that are $30 or more")
print("Delivery cost is an additional $5 for food orders below $30\n")
name = input("What is your name?\n")
print("\nHello " + name + "\n")
while finished == False:
try:
burgerselect = input("Please select which burger:\n")
if burgerselect == "cheeseburger":
quantityburger += int(input("How many would you like?\n"))
except ValueError:
print("Not valid")
continue
if burgerselect != "cheeseburger":
print("Not on our menu!\n")
else:
print("good choice\n")
price += 2.5 * quantityburger
try:
chipselect = input("Please select what size chips:\n")
if chipselect == "small":
quantitychips += int(input("How many would you like?\n"))
except ValueError:
print("Not valid")
continue
if chipselect != "small":
print("Not on our menu!\n")
else:
print("good choice\n")
price += 1.50 * quantitychips
try:
drinkselect = input("Please select which drink:\n")
if drinkselect == "cola":
quantitydrink += int(input("How many would you like?\n"))
except ValueError:
print("Not valid")
continue
if drinkselect != "cola":
print("Not on our menu!\n")
else:
print("good choice\n")
price += 1 * quantitydrink
deliveryselect=input('Would you like delivery? \n Yes: Delivery\n No: No delivery \n \n')
if deliveryselect=='Yes'or deliveryselect=='yes':
print('Thank You\n')
if price <= 30:
price += 5
elif price > 30:
price += 0
finished == True
break
elif deliveryselect =='No' or deliveryselect=='no':
print('Thank you\n')
finished == True
break
print(f"Your total cost is {price}!")
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. Can someone show me where I did wrong? I would appreciate any feedback on my code to the problem posted below. I'm a beginner and have only 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)
print_receipt(comp_name, sales_amount, select_item)
bonus = get_bonus(commission)
commission = commission + bonus
print_totals(bonus, commission)
def welcome_message():
print("Welcome to your commission calculator (v3)!")
def print_receipt(comp_name, sales_amount, select_item):
sub_total = 0
count = 0
print("\nCompany Name Unit Price Total Price")
print("------------ ---------- -----------")
while count < num_items:
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("Subtotal: $", format(sub_total, ".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()
You're passing 'sales_amount', which is a list, to 'get_commission_calc', which then compares the list with a number; hence the error.
What I believe you're trying to do is not passing the list, but the 'selected_item' of the list.
If that's the case, the function call should look more like this:
get_commission_calc(sales_amount[selected_item])
I have a problem with a while loop. Basically the program should continuously ask the user to input the item price until they enter 'Done', and print the total bill. For context I'll put my code at the moment.
a = float(input('Price? '))
count = 0
while a > 0:
b = float(input('Price? '))
count += b
if a == 'Done':
print('Total is $', count)
count = 0
while True:
a = input('Price? ')
if a == 'Done':
print('Total is $', count)
break
count += float(a)
Note that this code breaks if the user inputs a string that is not either "Done" or a float literal. For that you would need to surround the count += float(a) line with a try / except block.
here is my current code:
total = 0.0
count = 0
data = input("Enter a number or enter to quit: ")
while data != "":
count += 1
number = float(data)
total += number
data = input("Enter a number or enter to quit: ")
average = total / count
if data > 100:
print("error in value")
elif data < 0:
print("error in value")
elif data == "":
print("These", count, "scores average as: ", average)
The only problem now is "expected an indent block"
I would do something cool like
my_list = list(iter(lambda: int(input('Enter Number?')), 999)) # Thanks JonClements!!
print sum(my_list)
print sum(my_list)/float(len(my_list))
if you wanted to do conditions, something like this would work
def getNum():
val = int(input("Enter Number"))
assert 0 < val < 100 or val == 999, "Number Out Of Range!"
return val
my_list = list(iter(getNum, 999)) # Thanks JonClements!!
print sum(my_list)
print sum(my_list)/float(len(my_list))
To calculate an average you will need to keep track of the number of elements (iterations of the while loop), and then divide the sum by that number when you are done:
total = 0.0
count = 0
data = input("Enter a number or enter 999 to quit: ")
while data != "999":
count += 1
number = float(data)
total += number
data = input("Enter a number or enter 999 to quit: ")
average = total / count
print("The average is", average)
Note that I renamed sum to total because sum is the name of a built-in function.
total = 0.0
count = 0
while True:
data = input("Enter a number or enter 999 to quit: ")
if data == "999":
break
count += 1
total += float(data)
print(total / count)