I'm nearly finishing this project but still get an error saying my code doesn't accept invalid inputs, for example...if I input a string instead of an integer throws an error instead of accepting and show a message.
This is the error i get...
Any help would be really appreciated!
:( coke rejects invalid amount of cents
Did not find "50" in "Amount Due: 20..."
the code:
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()
CodePudding user response:
You have to remove any excess '
and "
from your string input.
This can be done with the .replace
method:
def main():
total = 0
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()
CodePudding user response:
If you mean to show a message if the input can't be converted to an integer, then you can simply do:
def main():
total = 0
while True:
try:
total = int(input("Insert one coin at a time: ").strip())
except Exception as e:
print("Your input is invalid, try again")
# Optionally you can continue or exit here
continue
# exit()
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()