Building a very simple vending machine in Python - python

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

Related

How to permanently change a variable in Python?

I decided to make a code in Python that is like an ATM Machine, and Everything works very well, you can check your balance, extract or add money,and change the PIN code. But when I change the PIN code i tried to assign the "changed_pin_code" variable to the "real_pin_code" variable,and it doesen't work, the PIN code remains the same. If you could give me some ideas on how I could solve the problem, or improve my code, that would be fantastic.
I am at the beggining with coding, and I am doing this so I can test my knowledge.
I left the code below.
def atm_machine():
code = input("Enter yout PIN code:")
pin_code = int(code)
real_pin_code = 4137
balance = 10000
if pin_code == real_pin_code:
print("""
ATM
1)Check Balance
2)Add money
3)Extract money
4)Change PIN code\n""")
number_select = int(input("Select a number:"))
if number_select > 4 and number_select == 0:
print("You must select a number between 1 and 4!")
atm_recall()
if number_select == 1:
print("Your current balance is:", balance, "$")
atm_recall()
if number_select == 2:
money_add = int(input("Enter amount of money you want to add:"))
new_money = balance + money_add
print("Your current balance is:", new_money, "$")
atm_recall()
if number_select == 3:
money_extract = int(input("Enter the amount of money you want to extract:"))
if money_extract > balance:
print("Insufficent fund")
atm_recall()
if money_extract <= balance:
remained_money = balance - money_extract
balance = remained_money
print("Your current balance is:", remained_money, "$")
atm_recall()
if number_select == 4:
measure_pin = 9999
changed_pin_code = int(input("Enter new PIN code:"))
if changed_pin_code == real_pin_code:
print("You can't enter the same PIN code:")
print("Wait for yout card!")
atm_recall()
if changed_pin_code > measure_pin:
print("PIN code must be formed of 4 digits!")
print("Wait for your card")
atm_recall()
else:
real_pin_code = changed_pin_code
print("PIN code succesfully changed!")
print("Your new PIN code is:", changed_pin_code)
atm_recall()
else:
print("PIN code inccorect!")
print("Wait for your card!")
def atm_recall():
question = str(input("To make another action, type \"Y\",else, type\"N\" "))
if question == "Y":
result = atm_machine()
return result
if question == "N":
print("Good Bye!")
print("Wait for your card!")
atm_machine()
The problem you are currently facing is because at end of each option you call atm_recall function, in which if the user selects the 'Y' option, it calls the atm_machine function which whenever called starts with real_pin_code set to 4137.
Solution:
As already mentioned by others, in comments what you should rather do is get rid of the recursion as it uses up a lot of memory and fills up the call stack on each function call. So a refactored approach would be something like this:
real_pin_code = 4137
balance = 10000
while True:
code = input("Enter yout PIN code:")
pin_code = int(code)
if pin_code == real_pin_code:
print("""
ATM
1)Check Balance
2)Add money
3)Extract money
4)Change PIN code\n""")
number_select = int(input("Select a number:"))
if number_select == 1:
print("Your current balance is:", balance, "$")
elif number_select == 2:
money_add = int(input("Enter amount of money you want to add:"))
balance = balance + money_add
print("Your current balance is:", balance, "$")
elif number_select == 3:
money_extract = int(input("Enter the amount of money you want to extract:"))
if money_extract > balance:
print("Insufficent fund")
else:
remained_money = balance - money_extract
balance = remained_money
print("Your current balance is:", remained_money, "$")
elif number_select == 4:
measure_pin = 9999
changed_pin_code = int(input("Enter new PIN code:"))
if changed_pin_code == real_pin_code:
print("You can't enter the same PIN code:")
print("Wait for yout card!")
elif changed_pin_code > measure_pin:
print("PIN code must be formed of 4 digits!")
print("Wait for your card")
else:
real_pin_code = changed_pin_code
print("PIN code succesfully changed!")
print("Your new PIN code is:", changed_pin_code)
else:
print("You must select a number between 1 and 4!")
else:
print("PIN code inccorect!")
print("Wait for your card!")
question = str(input("To make another action, type \"Y\",else, type\"N\" "))
if question == "N":
print("Good Bye!")
print("Wait for your card!")
break
Changes:
I took real_pin_code out of the loop, so its value doesn't reset at each iteration.
Also, for the same reason I took balance out of the loop and made the changes to balance itself rather than declaring a new variable new_money.
Also, as a good programming practice I changed a lot of if statements to elif and else where the conditions were exclusive of each other.
Better Approach:
A better approach, as already highlighted by others would be to use class where you would initialize an ATMMachine object with all the required details. However the approach you choose, mostly all the logic would remain the same except some refactoring and specific methods for each task.
I'm not sure if it's a best way to do it, but I would create a txt file with atm pin which You could read in the beggining to take pin code and write it when You want to change it. Something like this:
def atm_machine():
code = input("Enter yout PIN code:")
pin_code = int(code)
real_pin = open("code.txt", "r")
real_pin_code = int(real_pin.read())
Here I already have a txt file with some code created in program folder so python could read it, and here I'm saving new pin to same txt file:
else:
real_pin = open("code.txt", "w")
real_pin.write(str(changed_pin_code))
print("PIN code succesfully changed!")
print("Your new PIN code is:", changed_pin_code)
atm_recall()
Hope this helps anyhow.

Expected expression ATM

I was following along with a youtube video to a ATM using python and I got expected expression. I dont know how to fix it. line 32, 37 and 40.
enter image description here
You can't have an elif after an else. This is because else will capture all the remaining cases. Indentation, meaning spaces or tabs before the line is very important in Python.
Here is what I think you meant to write:
balance = 1000
print("""
Welcome to Dutch Bank
Choose Transaction
1) BALANCE
2) WITHDRAW
3) DEPOSIT
4) EXIT
""")
while True:
option = int(input("Enter Transaction"))
if option == 1:
print ("Your Balance is", balance)
anothertrans = input("Do You Want to make another Transaction? Yes/No: ")
if anothertrans == "YES":
continue
else:
break
elif option == 2:
withdraw = float(input("Enter Amount To Withdraw"))
if (balance > withdraw):
total = balance - withdraw
print("Success")
print("Your New Balance is: ",total)
else:
print("Insufficient Balance")
elif option == 3:
deposit = float(input("Enter Amount To Deposit"))
totalbalance = balance + deposit
print("Sucess")
print("Total Balance Now is: ", totalbalance)
elif option == 4:
print("Thank You ForBanking With Dutch Bank")
exit()
else:
print ("No selected Transaction")

Implement program to accept only certain coins

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

Python - Does input keep a value if not stored in a variable?

So I am doing a roulette like loop, which works well, except it sometimes stop at the "# end condition" part (10 lines up from bottom), often after 2 loops. Is there something to know about input() keeping its value or something like that even without a var or am I doing something wrong ?
# -*-coding:utf-8 -*
import os, math, random
user_number = 50
cash = 0
balance = 0
go_on = True
while go_on:
# to_find init
to_find = random.randrange(50)
# bet and cash init
if cash == 0:
temp = input("How many cash do you bet ?\n")
if int(temp) > 0:
cash = int(temp)
else:
continue
temp = input("Which number do you bet on (0 to 49) ?\n")
if int(temp) >= 0 and int(temp) <= 49:
user_number = int(temp)
else:
continue
# cash modif
if user_number == to_find:
balance += cash * 3
cash *= 4
print("Woot we got a winner\nYou're now at,", cash, "$ !\nThe number was", to_find, "\n")
elif user_number % 2 == to_find % 2:
balance += math.ceil(cash / 2)
cash = cash + math.ceil(cash / 2)
print("Yay you got some money\nYou're now at", cash, "$ !\nThe number was", to_find, "\n")
else:
balance -= cash
cash = 0
print("Sometime you win... And sometime, you're back to 0 !\nThe number was", to_find, "\n")
# end condition
print("Your current balance is at", balance, "\n")
if input("Want to try again ? Hit enter ! \nElse enter a number\n") == "":
pass
else:
go_on = False
print("See you soon !")
if balance < 0:
print(" And better luck next time !")
os.system("pause")
You have an infinite loop: If you hit the bottom of the loop while cash is not 0, then on the next iteration, you'll hit the else part of your cash == 0 condition whose continue takes you back to the beginning of the loop, which will then repeat forever.
Looking at what you are trying to do, my best guess would be that you have assumed that continue works like pass (which does nothing, and is equivalent to omitting the else-part entirely).
In order to figure out what is going on is situations like these, it might be a good investment to get familiar with a debugger, which would allow you to stop the code at any line and investigate the values of each of your local variables. There are plenty of those around, but an example of a good free one is PyCharm Community.

(Python) Vending Machine program returning wrong amount of money inserted? [closed]

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

Categories