How to create a shopping cart calculator - python

I am writing a program which takes one input (a number of product) and gives one output (price of the product):
Drink: $2.25
6-pack: $10
25% discount if more than $20
((Sorry if my code is really bad I'm a newbie))
print( "How many drinks do you want?" )
drinks = input( "Enter number: ")
total = int(drinks)
single = 2.25
six = 10
single * 6 = six
if total > 20:
total * 0.75
print( "That will be a total of: ", total, "dollars")
I'm confused how to make it so that, after I have changed the input value to an int, how can I separate and calculate it based on my pricing criteria. Please help?

I assume you're looking for something like this. Hope it helps! I tried to keep your variable names the same so it would make some kind of sense to you. The line I commented out is an error.
drinks = input("How many drinks do you want?")
drinks = int(drinks)
total = 0
single = 2.25
six = 10
sixPacks = drinks // 6
singles = drinks % 6
# single * 6 = six
total += six * sixPacks
total += single * singles
if total > 20:
total *= 0.75
print( "That will be a total of: {} dollars".format(round(total, 2)))

Okay so let's break it down logically.
You first take in the input number of drinks the person wants. You're assigning it to total right away, when you should actually assign it to a variable that holds the number of drinks.
You should then multiply the number of drinks by the cost per drink. You also need to check if the number of drinks are a multiple of 6 so that you can price them by the six pack.
Once you have calculated this check if the total < 20.
Since this is a homework problem. I will encourage you to try to solve it with this approach.

Related

index element creates not needed input

I want to make a code that would propose a customer one or more of products to add to his shop list if he has total cart less than available budget (for example, he bought products for 120 dollars, and program should ask him if he want to add one or a couple of products (for example for 20 and 30 dollars) in list so budget gets close to 150 dollars limit)
My problem here is that somehow i += 1 creates an unwanted input() process which i cannot explain
I am a newbie in Python so maybe someone can propose the solving of problem or even better version of my code, i'll be greatful for every help!
https://ibb.co/vJwhMw0 link for image here
inp = 'bar'
product_list = ['bar', 'bread', 'milk', 'coconut']
product_price = [10, 24, 30, 25]
indx = product_list.index(inp)
price = product_price[indx]
budget = 150
total = 120
proposal_list = ''
i = 0
while total < budget:
if (product_price[i] + total) <= budget:
total += product_price[i]
proposal_list += product_list[i]
i = i + 1
print (f'You can also add: {proposal_list}')
There is some problems with your code. No unwanted input() is created it's just that your while loop is infinite because i never changes because the condition is never true at some point.
while total < budget:
if i >= len(product_price):
break
elif (product_price[i] + total) <= budget:
total += product_price[i]
proposal_list += product_list[i]
i += 1
You code got inside infinite loop right after this line:
while total < budget:
Once the code inside this line is executed
if (product_price[i] + total) <= budget:
total become equal 130. Condition total < budget is still true but condition
if (product_price[i] + total) <= budget:
is not.
You need to exit the while loop. You can't do it until you update total.

Pounds and Ounces in Python

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))

Coin Change Maker Python Program

I am in a beginner programming course. We must do an exercise where we make a change maker program. The input has to be between 0-99 and must be represented in quarters, dimes, nickles, and pennies when the input is divided down between the four. I wrote a code that involved loops and whiles, but he wants something more easy and a smaller code. He gave me this as a way of helping me along:
c=int(input('Please enter an amount between 0-99:'))
print(c//25)
print(c%25)
He told us that this was basically all we needed and just needed to add in the dimes, nickles, and pennies. I try it multiple ways with the dimes, nickles, and pennies, but I cannot get the output right. Whenever I enter '99', I get 3 for quarters, 2 for dimes, 1 for nickles, and 0 for pennies. If anyone would be able to help me, that would be wonderful!
I'm now sure about what you want to achieve. Using the modulo operator you could easily find out how many quarters, dimes, nickles and pennies.
Let's just say you input 99.
c=int(input('Please enter an amount between 0-99:'))
print(c//25, "quarters")
c = c%25
print(c//10, "dimes")
c = c%10
print(c//5, "nickles")
c = c%5
print(c//1, "pennies")
this would print out:
3 quarters
2 dimes
0 nickles
4 pennies
n = int(input("Enter a number between 0-99"))
q = n // 25
n %= 25
d = n // 10
n %= 10
ni = n // 5
n %= 5
c = n % 5
print(str(q) +" " + str(d) +" " + str(ni) + " " + str(c))
I hope this helps? Something like this but don't just copy it. Everytime you divide by 25 10 5 you must lose that part because it's already counted.At the end print what ever you want :).
The actual trick is knowing that because each coin is worth at least twice of the next smaller denomination, you can use a greedy algorithm. The rest is just implementation detail.
Here's a slightly DRY'er (but possibly, uh, more confusing) implementation. All I'm really doing differently is using a list to store my results, and taking advantage of tuple unpacking and divmod. Also, this is a little easier to extend in the future: All I need to do to support $1 bills is to change coins to [100, 25, 10, 5, 1]. And so on.
coins = [25,10,5,1] #values of possible coins, in descending order
results = [0]*len(coins) #doing this and not appends to make tuple unpacking work
initial_change = int(input('Change to make: ')) #use raw_input for python2
remaining_change = initial_change
for index, coin in enumerate(coins):
results[index], remaining_change = divmod(remaining_change, coin)
print("In order to make change for %d cents:" % initial_change)
for amount, coin in zip(results, coins):
print(" %d %d cent piece(s)" % (amount, coin))
Gives you:
Change to make: 99
In order to make change for 99 cents:
3 25 cent piece(s)
2 10 cent piece(s)
0 5 cent piece(s)
4 1 cent piece(s)
"""
Change Machine - Made by A.S Gallery
This program shows the use of modulus and integral division to find the quarters, nickels, dimes, pennies of the user change !!
Have Fun Exploring !!!
"""
#def variables
user_amount = float(input("Enter the amount paid : "))
user_price = float(input("Enter the price : "))
# What is the change ?? (change calculation)
user_owe = user_amount - user_price
u = float(user_owe)
print "Change owed : " + str(u)
"""
Calculation Program (the real change machine !!)
"""
# Variables for Calculating Each Coin !!
calculate_quarters = u//.25
# Using the built-in round function in Python !!
round(calculate_quarters)
print "Quarters : " + str(calculate_quarters)
u = u%0.25
calculate_dime = u//.10
round(calculate_dime)
print "Dime : " + str(calculate_dime)
u = u%0.10
calculate_nickels = u//.05
round(calculate_nickels)
print "Nickels : " + str(calculate_nickels)
u = u%0.5
calculate_pennies = u//.01
round(calculate_pennies)
print "Pennies : " + str(calculate_pennies
Code for the change machine works 100%, its for CodeHs Python
This is probably one of the easier ways to approach this, however, it can also
be done with less repetition with a while loop
cents = int(input("Input how much money (in cents) you have, and I will tell
you how much that is is quarters, dimes, nickels, and pennies. "))
quarters = cents//25
quarters_2 = quarters*25
dime = (cents-quarters_2)//10
dime_2 = dime*10
nickels = (cents-dime_2-quarters_2)//5
nickels_2 = nickels*5
pennies = (cents-dime_2-quarters_2-nickels_2)

Rounding in Python

Hi everyone I am currently doing a school project and even my teacher is stumped. In Canada the penny has been removed so now all purchases are rounded to either 0 or 5. For example 5.53 would become 5.55 and 5.52 would become 5.50. I am trying to get my program to round like this, but I can't figure out how. I know how to round to decimal places, but I don't know how to round to specifics like this. Any help would be appreciated!
Here is my code. The project is about making a program that a cashier would use in a coffee shop.
order = ['coffee', 'tea', 'hashbrown','jelly','cream','chocolate','glazed','sandwich','bagel','cookie','pannini']
quantity = ['0','0','0','0','0','0','0','0','0','0','0']
# coffee = $1
# Tea = $1.30
# hashbrown = $1.25
# all donuts = $1.50
# sandwich = $2.50
# bagel = $2
# cookie = $0.50
# pannini = $4
cashier = 1
total = 0
while cashier == 1:
print "What did the customer order?"
ordered = input ()
while ordered > 10 or ordered < 0:
print "Do you want to input a valid order?"
ordered = input ()
print "How many are being ordered?"
quantityorder = input ()
quantity[ordered] = quantityorder
print "Ordered",quantityorder,"",order[ordered],"!"
if ordered == 0:
ordered = 1.0
elif ordered == 1:
ordered = 1.30
elif ordered == 2:
ordered = 1.25
elif ordered == 3 or ordered == 4 or ordered == 5 or ordered == 6:
ordered = 1.50
elif ordered == 7:
ordered = 2.50
elif ordered == 8:
ordered = 2
elif ordered == 9:
ordered = 0.50
else:
ordered = 4.0
price = ordered * quantityorder
total = total + price
print "Anything else?"
cashier = input () #If the user inputs 1 then they can input another order if they didn't put in 1 then the program assumes that it is the end of a customers order
print "Your total is $", total * 1.13,"!"
total = total * 1.13
print
print "How much money was given?"
print
money = input ()* 1.0
while money < total:
print "Please input a valid number!"
money = input ()
print "The change should be $",money - total,"!"
This tortured me until I solved it. One rule I set for myself was NOT to use a case-by-case switch on modulo 5, but to use builtin functions. Nice puzzle. wim's "double it, round, then halve it" comment was close.
def nickelround(n):
N = int(n)
print "%0.2f" % (N + round((n - N) * 20) * 0.05)
In [42]:
x=0.57
int(x/0.05)*0.05
Out[42]:
0.55
Usually in these programming problems you're explicitly asked to solve for how to "make change", not just provide the total amount of change due (which is trivial). So you can just in-line the pennies correction into that function:
def make_change(bal):
bal = bal + .02 #correction for no pennies
currency = [20,10,5,1,.25,.1,.05]
change = {}
for unit in currency:
change[unit] = int(bal // unit)
bal %= unit
return change
This particular form returns a dict of change denominations and their corresponding counts.
As you already hinted, use the Decimal class (module decimal). Replace all floats in your code with decimal constructors like Decimal('13.52').
Now the function you want to use is 'quantize'.
You use it like that:
Decimal('1.63').quantize(Decimal('0.5'), rounding=ROUND_HALF_DOWN)
The parameter Decimal('0.5') indicates that you want to round to the halves.
UPDATE:
As the OP wanted to round to the units of 0.05, he must obviously use:
Decimal('1.63').quantize(Decimal('0.05'), rounding=ROUND_HALF_DOWN)
I'm going to be old-school and say, convert your number into a list of values with a null or some kind of tag to represent the decimal.
The make a variable to hold your rounded number and add each value from 1000s or whatever, to 100s, 10s and 1s. (You are looping of course).
Once your loop hits the tag, depending on how far you want to round, (this should be a parameter for your function) throw in a conditional to represent how you want to round ie. 5 means round up, 4 round down (this is another parameter). Then add the final value(s) and return your newly rounded number.
Step 2: Fire your teacher because this is an unbelievably easy problem.
Bare in mind, anyone who knows c or has worked with memory assignment should find this question a breeze.
You could use something as simple as this to round your numbers to a given base:
def round_func(x, base=0.05):
return round(base*round(float(x)/base), 2)
And since you want only 2 decimal places, you can just round it to 2 decimals. The inner round function is to round the given number as per the base, which is 0.05 in your case.
Do you know, how to use own functions?
Add this function to your code:
def nickelround(m):
return round(m/0.05,0)*0.05
and use it:
print "The change should be $", nickelround(money - total),"!"

Python function: Find Change from purchase amount [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I'm looking for the most efficient way to figure out a change amount (Quarters, dimes, nickels, and pennies) from a purchase amount. The purchase amount must be less than $1, and the change is from one dollar. I need to know how many quarters, dimes, nickels, and pennies someone would get back.
Would it be best to set up a dictionary?
Gee, you mean this isn't problem 2b in every programming course any more? Eh, probably not, they don't seem to teach people how to make change any more either. (Or maybe they do: is this a homework assignment?)
If you find someone over about 50 and have them make change for you, it works like this. Say you have a check for $3.52 and you hand the cashier a twnty. They'll make change by saying "three fifty-two" then
count back three pennies, saying "three, four, five" (3.55)
count back 2 nickels, (3.60, 3.65)
count back a dime (3.75)
a quarter (4 dollars)
a dollar bill (five dollars)
a $5 bill (ten dollars)
a $10 bill (twenty.)
That's at heart a recursive process: you count back the current denomination until the current amount plus the next denomination comes out even. Then move up to the next denomination.
You can, of course, do it iteratively, as above.
This is probably pretty fast - just a few operations per denomination:
def change(amount):
money = ()
for coin in [25,10,5,1]
num = amount/coin
money += (coin,) * num
amount -= coin * num
return money
Your best bet is to probably have a sorted dictionary of coin sizes, and then loop through them checking if your change is greater than the value, add that coin and subtract the value, otherwise move along to the next row in the dictionary.
Eg
Coins = [50, 25, 10, 5, 2, 1]
ChangeDue = 87
CoinsReturned = []
For I in coins:
While I >= ChangeDue:
CoinsReturned.add(I)
ChangeDue = ChangeDue - I
Forgive my lousy python syntax there. Hope that's enough to go on.
This problem could be solved pretty easy with integer partitions from number theory. I wrote a recursive function that takes a number and a list of partitions and returns the number of possible combinations that would make up the given number.
http://sandboxrichard.blogspot.com/2009/03/integer-partitions-and-wiki-smarts.html
It's not exactly what you want, but it could be easily modified to get your result.
The above soloution working.
amount=int(input("Please enter amount in pence"))
coins = [50, 25, 10, 5, 2, 1]
coinsReturned = []
for i in coins:
while amount >=i:
coinsReturned.append(i)
amount = amount - i
print(coinsReturned)
Alternatively a solution can reached by using the floor and mod functions.
amount = int(input( "Please enter amount in pence" ))
# math floor of 50
fifty = amount // 50
# mod of 50 and floor of 20
twenty = amount % 50 // 20
# mod of 50 and 20 and floor of 10
ten = amount % 50 % 20 // 10
# mod of 50 , 20 and 10 and floor of 5
five = amount % 50 % 20 % 10 // 5
# mod of 50 , 20 , 10 and 5 and floor of 2
two = amount % 50 % 20 % 10 % 5 // 2
# mod of 50 , 20 , 10 , 5 and 2 and floor of 1
one = amount % 50 % 20 % 10 % 5 % 2 //1
print("50p>>> " , fifty , " 20p>>> " , twenty , " 10p>>> " , ten , " 5p>>> " , five , " 2p>>> " , two , " 1p>>> " , one )
Or another solution
amount=int(input("Please enter the change to be given"))
endAmount=amount
coins=[50,25,10,5,2,1]
listOfCoins=["fifty" ,"twenty five", "ten", "five", "two" , "one"]
change = []
for coin in coins:
holdingAmount=amount
amount=amount//coin
change.append(amount)
amount=holdingAmount%coin
print("The minimum coinage to return from " ,endAmount, "p is as follows")
for i in range(len(coins)):
print("There's " , change[i] ,"....", listOfCoins[i] , "pence pieces in your change" )
I have an improve solution from above solutions
coins=[]
cost = float(input('Input the cost: '))
give = float(input('Tipe Amount given: '))
change = (give - cost)
change2 = change-int(change)
change2 = round(change2,2)*100
coin = [50,25,10,5,1]
for c in coin:
while change2>=c:
coins.append(c)
change2 = change2-c
half=coins.count(50)
qua = coins.count(25)
dime=coins.count(10)
ni=coins.count(5)
pen=coins.count(1)
dolars = int(change)
if half !=0 or qua != 0 or dime!=0 or ni!=0 or pen!=0:
print ('The change of', round(give,2), 'is:',change, 'like \n-dolas:',dolars,'\n-halfs:',half,'\n-quarters:',qua,'\n-dime:',dime,'\n-nickels:',ni,'\n-pennies:',pen)
else:
print ('The change from', round(give,2), 'is:',change,'and no coins')

Categories