I've nearly finished my program but have to add a feature so it only accepts certain coins and will throw a message if a wrong coin is inserted.
any help would be appreciated
def main():
total = 0
coins = [10, 20, 30]
while True:
total += int(input("Insert one coin at a time: ").replace('"', '').replace("'", '').strip())
coke = 50
print(total)
if total > coke:
print("Change Owed =", total - coke)
return
elif total == coke:
print("No Change Owed, Here's a coke ")
return
else:
print("Amount Due =", coke-total)
main()
As suggested by #Barmar, create a list of allowed coins and make sure the input falls in the list:
def main():
total = 0
allowed_coins = [25,50,100]
coke = 50
while True:
coin_input = int(input("Insert one coin at a time: ").replace('"', '').replace("'", '').strip())
if coin_input not in allowed_coins:
print("Invalid Coin Amount Due =", coke - total)
return
total = total + coin_input
if total > coke:
print("Change Owed =", total - coke)
return
elif total == coke:
print("No Change Owed, Here's a coke ")
return
else:
print("Amount Due =", coke-total)
main()
You need to check the coin before adding it to total. If it's not valid, skip the rest of the loop and ask again
def main():
total = 0
coins = [10, 20, 30]
while True:
coin = int(input("Insert one coin at a time: ").replace('"', '').replace("'", '').strip())
if coin not in coins:
print("That's not an allowed coin, try again")
continue
total += coin
coke = 50
print(total)
if total > coke:
print("Change Owed =", total - coke)
return
elif total == coke:
print("No Change Owed, Here's a coke ")
return
else:
print("Amount Due =", coke-total)
main()
Related
I'm trying to build a vending machine with only one drink option that calculates the money inserted and memorises what was inserted and asks for the remaining money to be inserted...and if for example the money inserted still wasn't enough continues to ask and update the remaining until the price of the drink is reached...
Im nearly there, but somehow need to add a bit of code so the program memorises and keeps updating as new values are inserted until reaches the drink price
Any help would be really appreciated!!!
here's my code:
def main():
insert = int(input("Insert one coin at a time: ").strip())
coke = 50
total = coke - insert
while insert < coke:
print("Amount due: ", total)
return
if insert == coke:
print("Change Owed: ", total)
return
else:
print("Please insert the correct amount of: ", coke)
main()
I started by putting the variables first, then an infinite while loop exiting only when the amount is fulfilled Inserted == Coke while making sure to giveaway any change in case the amount inserted is superior to the price of the coke Inserted > Coke.
def main():
#Settings
Inserted = 0
Coke = 50
while True:
Inserted += int(input("Insert one coin at a time: "))
if Inserted > Coke:
print(f"Giving away {Inserted - Coke} as change ...")
break # Exiting the while loop
elif Inserted == Coke:
print("Enjoy your coke")
break #Exiting the while loop
else:
print(f"You have inserted {Inserted}c")
if __name__ == "__main__":
main()
Use break to exit the loop
There Were several errors:
You are only taking input once, you need to take it in every iteration of the loop
I think change owed should execute only when insert > coke
You need to correct the 2nd condition since if insert == coke, no change should be owed
Code to be used:
def main():
total = 0
while True:
total += int(input("Insert one coin at a time: ").strip())
coke = 50
print(total)
if total > coke:
print("Change Owed =", total - coke)
return
elif total == coke:
print("No Change Owed, Here's a coke ")
return
else:
print("Amount Due =", coke-total)
main()
Everytime that you check the insert with while insert < coke: you return, essentialy ending the program. Python does not store variables between different script executions. What you should do is use a while True loop and check if the total value is inserted.
def main():
total_insert = 0 # this variable will keep track of the total insert
coke = 50
while True: # use while True to create a loop that keeps on running.
insert = int(input("Insert one coin at a time: ").strip())
total_insert += insert
if total_insert < coke:
print("Amount due: ", coke-total_insert)
if total_insert == coke:
print("Here is a nice coke!")
break
if total_insert > coke:
print("Here is a nice coke and money:", total_insert-coke) # get the extra money
break
main()
You use the break statement to get out of the neverending while True loop if a certain condition is reached.
Consider this:
coke_price = 50
payment = coke_price
def main():
global coke_price
global payment
while True:
money_input = int(input("Enter one coin at a time: ").strip())
payment = payment - money_input
if payment < 0:
print("Change Owed =", -payment)
return
elif payment == 0:
print("No Change Owed, Here's a coke ", payment)
return
else:
print("Amount Due =", payment)
main()
I haven't polished the code but the functionality you desire is present within the algorithm. Hope this helps :D
P.S. I changed some variable names
#vending machine
def CountMoneyAndIssueDrink():
total_coins = 0
coke_price = 10
change = 0
while True:
insertedcoins = int(input("Insert coins:"))
total_coins += insertedcoins
print(total_coins ," total coins inserted")
if total_coins <= 0:
print("Insert some coins")
CountMoneyAndIssueDrink()
return
elif(total_coins > coke_price):
change = total_coins - coke_price
print("enjoy coke!!, here is the change:", change)
break
elif(total_coins == coke_price):
print("enjoy coke!!")
break
if __name__ == "__main__":
CountMoneyAndIssueDrink()
The program goes as follows, asks to choose a product, then asks for the amount of the choice, then the user inputs the amount, but if the amount is different from the declared values (mo), the program prints "wrong coins", but when the user inputs the correct coin and amount, it should print only the "change" part of the code. In my program, it prints "change" and then wrong coin value
prod = ["Coffe", "Coffee with milk", "Chocolate", "Chocolate with milk"]
cost = [1.5, 1.8, 2.1, 2.4]
mo = [0.1, 0.2, 0.5, 1, 2, 5, 10]
item_number = len(prod)
print("\nPick an item:")
for number in range(0, item_number, 1):
print(number + 1,
prod [number],
'{0:.2f}€'.format(cost[number]))
print ("0 Exit")
choice = int(input("Please pick an item from (1-4) or hit 0 to exit: ")) -1
if choice < item_number and choice >= 0:
print("You should input", "{0:.2f}€".format(cost[choice]), 'in total')
else:
print("Exiting the program")
exit(0)
money = float(input("How much do you enter?; "))
while money < cost[choice]:
money += float(input("You should insert "+str("{:.2f}".format(cost[choice] - money))))
if money != mo:
print("Invalid amount.\nPlease enter a valid coin: 0.1 / 0.2 / 0.5 / 1 / 2 / 5 / 10")
else:
print("Try again")
change = money - cost[choice]
print("Change {0:.2f}€".format(change))
The logic may be different
continuously ask for money (a while True allow to write the input once)
verify if the choosen is in the list not equal (a float can't be equal to a list)
increment your total money
stop if you have enough
money = 0
while True:
new_money = float(input(f"You should insert {cost[choice] - money:.2f}: "))
if new_money not in mo:
print("Invalid amount.\nPlease enter a valid coin: " + "/".join(map(str, mo)))
continue
money += new_money
if money >= cost[choice]:
break
change = money - cost[choice]
print(f"Change {change:.2f}€")
The other code, with some improvments
print("\nPick an item:")
for number in range(item_number, ):
print(f'{number + 1} {prod[number]} {cost[number]:.2f}€')
print("0 Exit")
choice = int(input("Please pick an item from (1-4) or hit 0 to exit: ")) - 1
if 0 < choice <= item_number:
print(f"You should input {cost[choice]:.2f}€", 'in total')
else:
print("Exiting the program")
exit(0)
The calculator does not recognize the price input being 60 as the first if statement, it will send you to else.
while True:
price = float(input("How much does it cost? (include cents!): $"))
discount=float(price)*100 / 1000
discount2=float(price)*200 /1000
proceed = 60
proceed2 = 120
if price >= proceed << proceed2:
print("Your new cost is")
print(round(price - discount, 2))
print("Press any key to exit")
input()
if price >= proceed2:
print("Your new cost is")
print(round(price - discount, 2))
print("Press any key to exit")
input()
else:
print("You are not viable for a discount, make a purchase >= sixty dollars to recive a 10% discount or a purchase >= $120 for a 20% discount.")
print("Press any key to exit")
input()
I fixed it, the first if statement used << when it should have used <.
while True:
price = float(input("How much does it cost? (include cents!): $"))
discount=float(price)*100 / 1000
discount2=float(price)*200 /1000
proceed = 60
proceed2 = 120
if price >= proceed < proceed2:
print("Your new cost is")
print(round(price - discount, 2))
print("Press any key to exit")
input()
if price >= proceed2:
print("Your new cost is")
print(round(price - discount, 2))
print("Press any key to exit")
input()
else:
print("You are not viable for a discount, make a purchase >= sixty dollars to recive a 10% discount or a purchase >= $120 for a 20% discount.")
print("Press any key to exit")
input()
Why am i getting this error? The picture has the details. I need to get the _spent values to print the proper amount of times. So, say it runs through the loop 3 times, I need it to print 3. I think that is where the 1s are coming from. I don't like it!
pennies = 10
nickels = 10
dimes = 10
quarters = 10
print("\nWelcome to change-making program.")
in_str = input("\nEnter the purchase price (xx.xx) or `q' to quit: ")
while in_str.lower() != 'q':
dollar_str, cents_str = in_str.split(".")
if in_str.lower() == 'q':
quit()
in_int = int(float(in_str) * 100)
if in_int < 0:
print("Error: purchase price must be non-negative.")
in_str = input("\nEnter the purchase price (xx.xx) or `q' to quit: ")
if in_int > 0:
payment = input("\nInput dollars paid: ")
payment_int = int(float(payment) * 100)
change = payment_int - in_int
#determines if there payment input
if payment_int < in_int:
print("Error: Insufficient payment.")
payment = input("\nInput dollars paid: ")
payment_int = int(float(payment) * 100)
if change == 0:
print("No change.")
#determines how many quarters, dimes, nickels, and pennies are left
while change >= 25 and quarters > 0:
change = change - 25
quarters_spent = 0
quarters_spent += 1
quarters = quarters - quarters_spent
print(quarters_spent)
while change >= 10 and dimes > 0:
change = change - 10
dimes_spent = 0
dimes_spent += 1
dimes = dimes - dimes_spent
print(dimes_spent)
while change >= 5 and nickels > 0:
change = change - 5
nickels_spent = 0
nickels_spent += 1
nickels = nickels - nickels_spent
print(nickels_spent)
while change >= 1 and pennies > 0:
change = change - 1
pennies_spent = 0
pennies_spent += 1
pennies = pennies - pennies_spent
if quarters == 0 and dimes == 0 and nickels == 0 and pennies == 0:
print("Error: ran out of coins.")
quit()
print("\nCollect Payment Below:")
print(10 - quarters, "Quarters")
print("\nStock: ", quarters, "Quarters, ", dimes, " Dimes, ", nickels, " Nickels, ", pennies, " Pennies ")
in_str = input("\nEnter the purchase price (xx.xx) or `q' to quit: ")
pennies = pennies
nickels = nickels
dimes = dimes
quarters = quarters
This error implies that you didn't define the value nickels_spent before trying to use it.
I guess the error is in this line: print (nickels_spent).
What is probably happening is that the while statement condition that is used to assign a value to that variable is not true when you try to run it, so it wasn't defined but you still try to use it.
Try debugging before that while loop to see what exactly happens there.
You only defined and initialized this variable nickels_spent inside the while loop
However, if the condition is not met, the program will skip the loop and jump to execute this print(nickels_spent) statement where this variable is not yet defined.
You can either
Move the print statement into the while loop
Or
Define and initialize this variable outside the while loop.
Depends on the purpose of your program
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I just recently started teaching myself Python (3.5.1) and have written a few basic programs. I am trying to write a program that allows a user to purchase 3 products maximum. However, I am having trouble with getting the correct value for the total amount of money inserted, which I am guessing is because it keeps re-initializing itself. Any help is appreciated. Also, is my code too complicated and if so, how can I simplify it?
Updated Code:
def main():
displayPrices()
purchaseItems()
def displayPrices():
print("Item ID:\tCost: ")
print("1\t\t$1.25")
print("2\t\t$0.75")
print("3\t\t$0.90")
print("4\t\t$0.75")
print("5\t\t$1.50")
print("6\t\t$0.75")
def purchaseItems():
choice=""
numItems=0
totalCost=0
totalReturned=0
item=0
change=0
x=0
money=float(input("Insert the amount of money you would like to input: $"))
totalInserted=money
while x < 3:
item=int(input("\nWhich item would you like to purchase?\nIf you would like to quit, enter '0': "))
if item == 1:
cost = 1.25
elif item == 2:
cost = .75
elif item == 3:
cost = .90
elif item == 4:
cost = .75
elif item == 5:
cost = 1.50
elif item == 6:
cost = .75
elif item == 0:
print("Thank you for using our Vending Machine. Goodbye!")
break
else:
print("Error. Please enter a valid Item ID [1-6]")
if cost <= money:
change = money - cost
numItems+=1
money=change
totalCost=totalCost+cost
totalReturned=change
print("Thank you for purchasing Item " + str(item) + ". Your change is $" + str(round(change,2)) + ".\n")
x+=1
else:
moneyNeeded = cost - money
print("Please enter an additional $" + str(moneyNeeded) + " to purchase your item.")
newMoney=float(input("Insert the amount of money you would like to input: $"))
totalInserted=money=money+newMoney
# End of Loop
print("Numbers of Items Purchased:", numItems)
print("Total cost of all Items Purchased:", totalCost)
print("Total amount of money inserted:", round(totalInserted,2))
print("Total amount of change returned:", round(totalReturned,2))
main()
Take a look at the following output:
Item ID: Cost:
1 $1.25
2 $0.75
3 $0.90
4 $0.75
5 $1.50
6 $0.75
Insert the amount of money you would like to input: $0
Which item would you like to purchase?
If you would like to quit, enter '0': 1
Please enter an additional $1.25 to purchase your item.
Insert the amount of money you would like to input: $1.00
Which item would you like to purchase?
If you would like to quit, enter '0': 2
Thank you for purchasing Item 2. Your change is $0.25.
Which item would you like to purchase?
If you would like to quit, enter '0': 1
Please enter an additional $1.0 to purchase your item.
Insert the amount of money you would like to input: $1.0
Which item would you like to purchase?
If you would like to quit, enter '0': 1
Thank you for purchasing Item 1. Your change is $0.0.
Which item would you like to purchase?
If you would like to quit, enter '0': 0
Thank you for using our Vending Machine. Goodbye!
Numbers of Items Purchased: 2
Total cost of all Items Purchased: 2.0
Total amount of money inserted: 1.25 --- This is incorrect
Total amount of change returned: 0.0
I was surprised this line even ran without error, but apparently it's a valid construct:
totalInserted=money=money+newMoney
In that line totalInserted is getting assigned the value of money. However, money currently available is not the same as totalInserted. What you really want is this:
money += newMoney
totalInserted += newMoney
As for if your code is too complicated, one suggestion to make it simpler would be to store the item/price relationship in a dictionary:
prices = {1:1.25, 2:.75, ...}
Then later you can just do this:
cost = prices[item]
You'd still need to first check if item was 0 or an invalid input. You also have a variable, choice that is never used.
Here may be one solution.
def main():
displayPrices()
purchaseItems()
def displayPrices():
print("Item ID:\tCost: ")
print("1\t\t$1.25")
print("2\t\t$0.75")
print("3\t\t$0.90")
print("4\t\t$0.75")
print("5\t\t$1.50")
print("6\t\t$0.75")
def purchaseItems():
money = float(input("How much money would you like to insert?"))
moneyInserted = money
items_sold = 0
items = [1.25, .75, .9, .75, 1.5, .75]
moneySpent = 0
total_cost = 0
x = 1
while x != 0 and money > 0 and items_sold < 3:
print("You have $" + str(money) + " left.")
x = int(input("What item would you like to buy?"))
if x == 0:
pass
elif x < 1 or x > 6:
print("Please return a valid item number.")
elif money >= items[x-1]:
print("Thank you for buying item "+str(x)+".")
money -= items[x-1]
moneySpent += items[x-1]
total_cost += items[x-1]
items_sold += 1
else:
pass
print("Number of items sold: " + str(items_sold))
print("Money Inserted: " + str(moneyInserted))
print("Amount of money spent: " + str(total_cost))
print("Change amount: " + str(money))
main()