'Simple vending machine with one drink in python
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()
Solution 1:[1]
If you can't fulfill the requirement because your code should accept invalid inputs, for example letters, and not crash, you could try the following with a try-expect-block
def main():
total = 0
while True:
try:
total += int(input("Insert one coin at a time: ").strip())
except ValueError:
print("The input is not a number, please only enter numbers")
else:
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()
For more information about using exception i would suggest you to read the Python-documentation
Solution 2:[2]
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()
Solution 3:[3]
when you say you input a string, do you mean like "20" with quotation marks?
if so put .replace('"','').replace("'","") next to .strip() will sort that out to get rid of " and ' .
total += int(input("Insert one coin at a time: ").strip().replace('"','').replace("'",""))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mime |
| Solution 2 | Nin17 |
| Solution 3 | tgm_learn |
