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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.