I'm trying to get the user to be able to input several values into the cash register. When they are done, all they have to type in is -1 and it won't request any more values to be input. Once this is done, the program adds up the total of the numbers input, and then spits them out in a message as netPrice. grossPrice however adds them up but adds 10% GST to the end value. I've had no experience with raw_input or continuing variables, and searching here I found some information that I attempted to apply to the code, however failed for me.
#x = continued input ("Enter in net price of items for the cash register: ")
#if x -1:
# stop;
#netPrice = x
#grossPrice = netPrice + (0.1 * netPrice)
#print ("The net price of all items is: $",netPrice)
#print ("The gross price of all items (this includes GST) is: $",grossPrice)
x = raw_input("Enter in net price of items for the cash register: ")
if x >=-1:
stop;
netPrice = x
grossPrice = netPrice + (0.1 * netPrice)
print ("The net price of all items is: $",netPrice)
print ("The gross price of all items (this includes GST) is: $",grossPrice)
You can do something as follows:
values = []
while True:
x = float(input('Enter in net price of items for the cash register: '))
if x == -1:
break
values.append(x)
print ("The net price of all items is: " + str(sum(values)))
Related
My teacher gave me this assigment"Write a program that calculates the bill of sale for three items purchased. The cost of each item will be read from the user and stored into variables. The receipt will show the number of items purchased, the cost of each item, the average cost per item, the tax rate (.0825% in Texas), the tax amount, and the total cost" I'was able to do it with basic input and variables but i had some trouble when he asked me to use format() in the code because there's always a different error. Here's my attempt.
cost_1 = float(input("Enter cost of item 1:"))
cost_2 = float(input("Enter cost of item 2:"))
cost_3 = float(input("Enter cost of item 3:"))
cost = ['cost_1', 'cost_2', 'cost_3']
sentence = 'Cost 1: {0} Cost 2: {1} Cost 3: {2}'.format(cost, float['cost_1'], cost, float['cost_2'], cost, float['cost_3'])
print(sentence)
Average_cost = float(cost_1 + cost_2 + cost_3)/3
Total_cost = float(cost_1 + cost_2 + cost_3)
print("Average cost:", Average_cost)
print("Total cost:", Total_cost)
Tax_rate = float(8.25)
print("Tax rate:", Tax_rate)
Taxes = float(Total_cost*Tax_rate/100)
print ("Taxes:",float(Taxes))
Total = Total_cost + Taxes
print("Total:", Total)
I will not give you the answer, but I will explain a couple things you are doing wrong.
cost_1 = float(input("Enter cost of item 1:"))
cost_2 = float(input("Enter cost of item 2:"))
cost_3 = float(input("Enter cost of item 3:"))
# below you are assigning strings to the cost array, you should not have quotes here
cost = ['cost_1', 'cost_2', 'cost_3']
# below you are trying to format with three variables but are passing four.
# you are also trying to access the float function as a dict type.
sentence = 'Cost 1: {0} Cost 2: {1} Cost 3: {2}'.format(cost, float['cost_1'],
cost, float['cost_2'], cost, float['cost_3'])
print(sentence)
# there is no need to constantly float variables that are float
Average_cost = float(cost_1 + cost_2 + cost_3)/3
# agagin
Total_cost = float(cost_1 + cost_2 + cost_3)
print("Average cost:", Average_cost)
print("Total cost:", Total_cost)
# a float number is already a float, you dont need to declare it as float
Tax_rate = float(8.25)
print("Tax rate:", Tax_rate)
Taxes = float(Total_cost*Tax_rate/100)
print ("Taxes:",float(Taxes))
Total = Total_cost + Taxes
print("Total:", Total)
I will give you a little help with the cost list.
items_count = 3
cost = []
for i in range(items_count):
cost.append(float(input("enter price for item %d: " % (i+1))))
Also, there is a function called sum that will add up all the numbers in a list. Here is a tutorial https://www.programiz.com/python-programming/methods/built-in/sum
I was trying to print the output under the 2nd for loop (enter the amount Of $20: ...), but I am getting 0. How to fix this issue? The user gets amount of $20 : 1, and amount of $2.00: 2, when they input 22 from keyboard.
Code:
denomitions={"$20.00":0,
"$10.00":0,
"$5.00":0,
"$2.00":0,
"$1.00":0,
"$0.25":0,
"0.10":0,
"0.5":0}
dividers = [2000,1000,500,200,100,25,10,5]
number = float(input("please enter the amount for change:").strip("$"))
#convert dollar to cents
change = int(number*100)
for i in range(len(denomitions)):
amount = int(change/dividers[i])
change= change- amount * dividers[i]
#print the result out
index= float(dividers[i] / 100.00)
print(index,":",amount)
#print the result out
for k in denomitions:
print("amount of "+str(k),amount)
denomitions={"$20.00":0,
"$10.00":0,
"$5.00":0,
"$2.00":0,
"$1.00":0,
"$0.25":0,
"0.10":0,
"0.5":0}
dividers = [2000,1000,500,200,100,25,10,5]
#add an empty list
amount_list = []
number = float(input("please enter the amount for change:").strip("$"))
#convert dollar to cents
change = int(number*100)
for i in range(len(denomitions)):
amount = int(change/dividers[i])
change= change- amount * dividers[i]
#print the result out
index= float(dividers[i] / 100.00)
print(index,":",amount)
#fill the list with the amount at index i
amount_list.append(amount)
#print the result out
i = 0
for k in denomitions:
#now you can retrieve the amount from the list if you keep the same index
print("amount of "+str(k), str(amount_list[i]))
i += 1
The problem is that in the second for loop, it picks up the amount equal to the last round of the previous for loop. At the end of the first loop amount = 0, therefore you will always get zero when printing amount in the second for loop.
I know these are very basic questions but cannot figure out what I'm doing wrong. I'm just beginning to learn python and don't understand why I am getting a syntax error every time I try to subtract something.
When I try to run this:
```#def variables - input cash entered and item price in float parentheses
cash = float(400)
price = float(215)
#change calculation
def cash_owed(cash - price)```
I get a
SyntaxError: invalid syntax with the ^ pointing to the - sign.
I can't find any information about why using a subtraction sign would return a syntax error in this context. What am I doing wrong?
I am trying to create a coin machine program where the cash is entered in integers representing cents (i.e $5 = 500) returns the required change in the most convenient coin denominations. This is the rest of the code that I wrote, but I can't even get past that first syntax error.
cash = float(400)
price = float(215)
#change calculation
def cash_owed(cash - price)
c = cash_owed
#display amount recieved, cost of item, required change
print ("Amount recieved : " + str(cash)) \n
print ("Cost of item : " + str(float)) \n
print("Required change : " + str(c)) \n
#calculate toonies owed
def calculate_toonies(c//200)
round(calculate_toonies)
print("Toonies x " + str(calculate_toonies))
c = c%200
#calculate loonies owed
def calculate_loonies(c//100)
round(calculate_loonies)
print("Loonies x " + str(calculate_loonies))
c = c%100
#calculate quarters owed
def calculate_quarters(c//25)
round(calculate_quarters)
print("Quarters x " + str(calculate_quarters))
c = c%25
#calculate dimes owed
def calculate_dimes(c//10)
round(calculate_dimes)
print("Dimes x " + str(calculate_dimes))
c = c%10
#calculate nickles owed
def calculate_nickles(c//5)
round(calculate_nickles)
print("Nickles x " + str(calculate_nickles))
c = c%5```
Your function definition is wrong. The parameter cannot do an operation & should contain a colon.
Change
def cash_owed(cash - price)
To
def cash_owed(cash, price):
new_price = cash - price
You have to put a colon after function
You can try this:
def cash_owed(cash, price):
return(cash - price)
I just started to learn coding and I'm having an issue trying to get the pounds converted over to ounces. We're suppose to allow the user to input their data like 6 pounds 2 ounces. I'm stuck at the moment and I'm not even sure if I'm going about this right. Any help would be appreciated.
Your program will accept as input the weights in pounds and ounces for a set of rabbits fed with one type of food. Let the user provide the name of food. Accept input until the user types a zero weight. Make life easier by converting weights to ounces. Compute the arithmetic mean (average) of each set of rabbits. Determine which set of rabbits weighs the most, reporting their average weight.
This was my orignal code before using pounds and ounces and it worked fine using simple number like 13.
f1 = input("Name of Food:")
print (f1)
counter = 0
sum = 0
question = input('''Enter a weight? Type "Yes" or "No" \n\n''')
while question == "Yes" :
ent_num = int(input("Weight of Rabbit:"))
sum = sum + ent_num
counter = counter + 1
question = input('''Enter another weight? Type "Yes" or "No". \n ''')
print ("Average weight " + str(sum/counter))
My current code looks like this after I tried to implement pounds and ounces into the input.
f1 = input("Name of Food: ")
print (f1)
counter = 0
sum = 0
print ("Please enter inforamtion in pounds and ounces. End")
question = input('''Enter a weight? Type "Yes" or "No" \n\n''')
while question == "Yes" :
ent_num = int(input("Weight of Rabbit:"))
sum = sum + ent_num
counter = counter + 1
if pounds * ounces == 0:
allOunces = pounds * 16 + ounces
sum = sum + allOunces
print ("Average weight " + str(sum/counter))
A big part of programming is learning how to cleanly break a big problem into smaller pieces.
Let's start by getting a single weight:
POUND_WORDS = {"pound", "pounds", "lb", "lbs"}
OUNCE_WORDS = {"ounce", "ounces", "oz", "ozs"}
OUNCES_PER_POUND = 16
def is_float(s):
"""
Return True if the string can be parsed as a floating value, else False
"""
try:
float(s)
return True
except ValueError:
return False
def get_weight(prompt):
"""
Prompt for a weight in pounds and ounces
Return the weight in ounces
"""
# We will recognize the following formats:
# 12 lb # assume 0 ounces
# 42 oz # assume 0 pounds
# 12 6 # pounds and ounces are implied
# 3 lbs 5 oz # fully specified
# repeat until we get input we recognize
good_input = False
while not good_input:
# get input, chunked into words
inp = input(prompt).lower().split()
if len(inp) not in {2, 4}:
# we only recognize 2-word or 4-word formats
continue # start the while loop over again
if not is_float(inp[0]):
# we only recognize formats that begin with a number
continue
# get the first number
v1 = float(inp[0])
if len(inp) == 2:
if inp[1] in POUND_WORDS:
# first input format
lbs = v1
ozs = 0
good_input = True
elif inp[1] in OUNCE_WORDS:
# second input format
lbs = 0
ozs = v1
good_input = True
elif is_float(inp[1]):
# third input format
lbs = v1
ozs = float(inp[1])
good_input = True
else:
# 4 words
if inp[1] in POUND_WORDS and is_float(inp[2]) and inp[3] in OUNCE_WORDS:
lbs = v1
ozs = float(inp[2])
good_input = True
return lbs * OUNCES_PER_POUND + ozs
Now we can use that to get the average of a bunch of weights:
def get_average_weight(prompt):
"""
Prompt for a series of weights,
Return the average
"""
weights = []
while True:
wt = get_weight(prompt)
if wt:
weights.append(wt)
else:
break
return sum(weights) / len(weights)
Now we want to get the average for each food type:
def main():
# get average weight for each feed type
food_avg = {}
while True:
food = input("\nFood name (just hit Enter to quit): ").strip()
if food:
avg = get_average_weight("Rabbit weight in lbs and ozs (enter 0 0 to quit): ")
food_avg[food] = avg
else:
break
# now we want to print the results, sorted from highest average weight
# Note: the result is a list of tuples, not a dict
food_avg = sorted(food_avg.items(), key = lambda fw: fw[1], reverse=True)
# and print the result
for food, avg in food_avg:
lbs = int(avg // 16)
ozs = avg % 16
print("{:<20s} {} lb {:0.1f} oz".format(food, lbs, ozs))
and then run it:
main()
This still takes some fussing around to get the average weight to print properly - our program needs to "know about" how weights are represented. The next step would be to push this back into a Weight class - ideally one which is agnostic about weight units (ie can accept arbitrary units like kilograms or pounds or stone).
You need to save the pounds and ounces in separate variable so something like this is needed.
f1 = input("Name of Food: ")
print (f1)
counter = 0
sum = 0
print ("Please enter inforamtion in pounds and ounces. End")
question = input('''Enter a weight? Type "Yes" or "No" \n\n''')
while question == "Yes" :
pounds, ounces = map(int, input().split())
weight = pounds * 16 + ounces
sum = sum + weight
counter = counter + 1
if pounds * ounces == 0:
print ("Average weight " + str(sum/counter))
There are a few issues with the second block of code.
1.
question = input('''Enter a weight? Type "Yes" or "No" \n\n''')
while question == "Yes" :
...
You need to ask your question inside the loop. You will loop endlessly because they never get asked to change question again inside the loop. What I would do is set question = "Yes" before the loop and then have the first line inside your loop be
question = input('''Enter a weight? Type "Yes" or "No" \n\n''')
2.
You need to decide how you want the user to enter input. You currently have
ent_num = int(input("Weight of Rabbit:"))
But ent_num could be anything from "6lbs 12oz" to "7pounds11ounces" to "potato". There's no consistent way to parse it unless you specifically tell them how to type out the weight. A less ambiguous way to ask this would be to say something like:
raw_input = input("Please enter the weight of the rabbit in pounds
and ounces with a space separating the two numbers (e.g. 7lbs 12oz):")
Then you can do something to recover the two separate numbers. Something like this should work.
#split the string by the space.
chunked_input = raw_input.split()
#get the digits in the two chunks
lbs, ounces = map(lambda x: int(filter(str.isdigit, x)), chunked_input)
Now that bit probably requires a bit of explanation. map here is taking a function (the lambda x bit) and applying that function to all the members of chunked_input. map(lambda x: x+2, [4, 6, 7]) == [6, 8, 9].
Lambdas are just a tool to make a quick function without having to name it. You could accomplish the same thing as the lbs, ounces line by writing your own function:
def get_digit(my_substring):
return int(filter(str.isdigit, my_substring)
and then mapping it:
lbs, ounces = map(get_digit, chunked_input)
Regardless, once you have the lbs and ounces as two separate variables, you're good to go. You can normalize them with the same formula you used:
weight = pounds * 16 + ounces
And then you'll eventually have the total weight in ounces of every weight entered.
To print out the average weight at the end you can do the division the way you did before:
#the * 1.0 is because if you can have fractional results, one of
#either the divisor or the dividend must be a float
avg_oz_weight = sum * 1.0/counter
and then if you want to display it in lbs and ounces, you need two useful operators, % and //. % is called the modulo operator, it returns the remainder when you're doing division so (7 % 3 == 1, 6 % 2 == 0). The // operator is floor division, so (7 // 3 == 2, 6 // 2 == 3).
So you can print a nice result with:
print("The average weight is: {}lbs {}oz".format(avg_oz_weight // 16,
avg_oz_weight % 16))
One of my school assignments is to create a program where you can input a minimum number of passengers, a max number of passengers, and the price of a ticket. As the groups of passengers increase by 10, the price of the ticket lowers by 50 cents. At the end it is supposed to show the maximum profit you can make with the numbers input by the user, and the number of passengers and ticket price associated with the max profit. This all works, but when you input numbers that result in a negative profit, i get a run time error. What am i doing wrong? I have tried making an if statement if the profit goes below 0, but that doesn't seem to work. here is my work for you all to see. A lead in the right direction or constructive criticism would be a great help.
#first variables
passengers = 1
maxcapacity = 500
maxprofit = 0
ticketprice = 0
fixedcost = 2500
#inputs and outputs
again = 'y'
while (again == 'y'):
minpassengers = abs(int(input("Enter minimum number of passengers: ")))
maxpassengers = abs(int(input("Enter maximum number of passengers: ")))
ticketprice = abs(float(input("Enter the ticket price: ")))
if (minpassengers < passengers):
minpassengers = passengers
print ("You need at least 1 passenger. Setting minimum passengers to 1.")
if (maxpassengers > maxcapacity):
maxpassengers = maxcapacity
print ("You have exceeded the max capacity. Setting max passengers to 500.")
print ("Passenger Run from", minpassengers, "to", maxpassengers, "with an initital ticket price of $",format (ticketprice, "7,.2f"), "with a fixed cost of $2500.00\n"
"Discount per ticket of $0.50 for each group of 10 above the starting count of", minpassengers, "passengers")
for n in range (minpassengers, maxpassengers + 10, 10):
ticketcost = ticketprice - (((n - minpassengers)/10) * .5)
gross = n * ticketcost
profit = (n * ticketcost) - fixedcost
print ("Number of \nPassengers", "\t Ticket Price \t Gross \t\t Fixed Cost \t Profit")
print (" ", n, "\t\t$", format (ticketcost, "7,.2f"), "\t$", format (gross, "5,.2f"), "\t$", format(fixedcost, "5,.2f"), "\t$", format (profit, "5,.2f"))
if (profit > maxprofit):
maxprofit = profit
maxpass = n
best_ticket = ticketcost
print ("Your max profit is $", format (maxprofit, "5,.2f"))
print ("Your max profit ticket price is $", format (best_ticket,"5,.2f"))
print ("Your max profit number of passengers is", maxpass)
again = input ("Run this again? (Y or N): ")
again = again.lower()
print ("\n")
This is happening because the condition profit > maxprofit never evaluates to True in the situation where your profit is negative, because maxprofit is set to 0 up at the top. This in turn means that best_ticket never gets assigned a value in this case, and so Python can't print it out later.
You could avoid this problem either by setting a default value for best_ticket earlier in the program:
best_ticket = 0
or by adding a condition that you only print out a best ticket price when best_ticket is set:
# Earlier in the program.
best_ticket = None
if best_ticket is not None:
print("Your max profit ticket price is $", format(best_ticket,"5,.2f"))
Also, FYI, the same problem will occur for the maxpass variable.
Your error is telling you the problem
NameError: name 'best_ticket' is not defined
You define best_ticket in this block
if (profit > maxprofit):
maxprofit = profit
maxpass = n
best_ticket = ticketcost
Regardless of the truth of that statement, you reference best_ticket below
print ("Your max profit ticket price is $", format (best_ticket,"5,.2f"))
Your error is probably because the variable you are outputting is defined in a spot that doesn't get executed.
if (profit > maxprofit):
maxprofit = profit
maxpass = n
best_ticket = ticketcost
So, whenever the if condition is False, best_ticket never gets assigned.
Try adding best_ticket = 0 at the top of your code.
ticketprice = abs(float(input("Enter the ticket price: ")))
best_ticket = -1 #nonsense value that warns you whats happening.