Can someone tell me how to fix the 1st inner loop? I want the user to be able to quit the program inputting quit but its not working

Joined
Mar 16, 2025
Messages
1
Reaction score
0
# chips = 1.00
# chocolate = 1.50
# soda = 1.20
# ch=("chips")
# cho=("chocolate")
# sod=("soda")
# while True:
# print("""Welcome to the Vending Machine!
# Items Available:
# 1. Chips - £1.00
# 2. Chocolate - £1.50
# 3. Soda - £1.20""")
#
# try:
# choice = int(input("Please select between 1-3: "))
#
# if choice in [1,2,3]:
# if choice==1:
# print(f"You selected {ch} which is £{chips}")
# price=chips
# elif choice ==2:
# print(f"you selected {cho} which is £{chocolate}")
# price=chocolate
# elif choice ==3:
# print(f"you selected {sod} which is £{soda}")
# price=soda
#
# else:
# print("Invalid please select between 1 and 3")
# continue
# except ValueError:
# print('Invalid Input, You must select a NUMBER between 1-3')
# continue
#
# s=True
#
# money = input('Please insert your money (CASH GBP Only) under £10: ')
# while True:
#
# if money.lower() == "quit":
# print("Transaction cancelled. Get your money up")
# s=False
# break
# try:
# money = float(money)
# if money > 10 or money<1:
# print("You cannot insert money greater or lower than £10 or enter " ,0.0)
# continue
#
# else:
# break
# except ValueError:
# print("Invalid input. Please enter a number. or enter [exit]")
# continue
#
#
#
#
#
#
#
#
# change= money-price
#
#
#
#
#
# if money < price:
# while True:
# print("You do not have enough!")
# change2 = input('Please insert more change or input "quit" to exit: ')
#
# # Check if the user wants to quit
# if change2.lower() == 'quit':
# print("Transaction cancelled. Get your money up")
# print("-" * 100)
# break
#
#
# try:
# change2 = float(change2)
# money+=change2
#
# if money >= price:
# if money == price:
# print("You have paid the exact amount. No change due.")
# print("-" * 100)
# break
#
# else:
# change2 = money - price
# print("You have paid the price of the product")
# print(f"Here's your change: £{round(change2, 2)}")
# print("-" * 100)
# break
#
# else:
# print(f"You still need £{price - money:.2f} more.")
# except ValueError:
# print("Invalid input. Please enter a valid amount or type 'quit' to exit.")
#
#
# elif money == price:
# print("You have enough to purchase this item.")
# print("Goodbye :)")
# print("-" * 100)
#
#
#
# elif money > price:
# print(f"Here is your change: ", round(change,3))
# print("Goodbye :)")
# print("-"*100)
#
 
Joined
Jul 4, 2023
Messages
585
Reaction score
78
# chips = 1.00
# chocolate = 1.50
# soda = 1.20
# ch=("chips")
# cho=("chocolate")
# sod=("soda")
Instead of assigning consecutive values to different variable names, use a list.
Python:
items = [
  {"name": "chips",     "price": 1.00},
  {"name": "chocolate", "price": 1.50},
  {"name": "soda",      "price": 1.20}
]


Have you tried writing it this way?

[ Working code online ]
Python:
import sys, os, time

items = [
  {"name": "chips",        "price": 1.00},
  {"name": "chocolate",    "price": 1.50},
  {"name": "gummy bears",  "price": 2.20},
  {"name": "water",        "price": 0.55},
  {"name": "juice",        "price": 1.30}
]


MIN_ITEM = 1
MAX_ITEM = len(items)
CURRENCY = "£"


def clear_screen():
    os.system("cls" if os.name == "nt" else "clear")
   
def highlight_text(text):
    return f"\033[30;102m {text} \033[0m"


while True:
  clear_screen()
  print(
    "Welcome to the Vending Machine!",
    "Items Available:",
    "----------------",
    sep="\n"
  )
  for i, item in enumerate(items, 1):
    print(f"{i}. {item["name"].capitalize()} - {CURRENCY}{item["price"]:.2f}")

  choice = 0  
  while True:
    try:
      choice = int(input(f"Please select between {MIN_ITEM}-{MAX_ITEM}: ")) - 1
      if 0 <= choice < len(items):
        break
      else:
        raise ValueError
    except ValueError:
      # Move the cursor back to the previous line and clear it
      sys.stdout.write("\033[A\033[K")
      sys.stdout.flush()
   

  current_balance = money = 0
  price = items[choice]["price"]
 
  while True:
    clear_screen()
    print(f"You selected {highlight_text(items[choice]["name"])} which costs {CURRENCY}{price:.2f}")
 
    try:
      money = input(f"Current balance: {CURRENCY}{current_balance:.2f}\nPlease insert your money: ")
     
      if money.lower() in ["q", "quit"]:
        clear_screen()
        print("Transaction cancelled. Get your money up.")
        time.sleep(4)
        break
     
      current_balance += float(money)
      if current_balance >= price:
        clear_screen()
        print(
          f"    You just bought: {highlight_text(items[choice]["name"])}",
          f"              Price: {CURRENCY}{price:.2f}",
          f"    Current balance: {CURRENCY}{current_balance:.2f}",
          f"Here is your change: {CURRENCY}{(current_balance - price):.2f}",
          sep="\n"
        )
       
        thanks = "Thank you for your purchase."
        print(
          f"\n{"-"*len(thanks)}",
          f"\n{thanks}",
          sep=""
        )
       
        time.sleep(8)
        break
       
    except ValueError:
      money = 0
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,302
Messages
2,571,545
Members
48,344
Latest member
Darcy80V04
Top