Home > Back-end >  How to print Congrats with out the error in python
How to print Congrats with out the error in python

Time:11-10

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

CodePudding user response:

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