0
from decimal import *
errors = "abcdffghijklmnopqrstuvwxyz?><:;\|{}[]"
purchase_price = Decimal(input("Please enter the price of your item"))
while purchase_price in errors:
    print("Please enter the price of your item ex: 123.45")
    break
else:

I'm having trouble checking if a character or characters in the errors var is being input.

When input is anything that is not a number

The Output is :

Traceback (most recent call last):
  File "C:/Users/Chris/PycharmProjects/Tax Calculator/main.py", line 4, in <module>
    purchase_price = Decimal(input("Please enter the price of your item"))
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]

If a character is there I would like to write a loop to give them another opportunity to to re-enter the price.

2
  • Why Decimal? Convert the input to float do like this, float(input("Please enter the price of your item")) It would cause an error if illegal char is entered Commented Feb 5, 2015 at 14:05
  • sailesh, just thought I'd note again that floats are not a good way to handle money, since usually good accuracy is important :) Commented Feb 5, 2015 at 14:06

2 Answers 2

1

If you want the input to be a number, I'd suggest making it a float and handling the exception if you cannot parse it:

try:
    purchase_price = float(input("Please enter the price of your item"))
except (ValueError, TypeError) as e:
    pass # wasn't valid, print an error and ask them again.

Though, please note that floats are not a good way to accurately handle money! This is a huge deal! You need to search online to find a good solution: http://code.google.com/p/python-money/

Sign up to request clarification or add additional context in comments.

2 Comments

Hey thanks for the help. I've got the money library up and running in place of Decimal. Could you explain the except portion for me? I got lost when I saw as e
That passes the exception object to e so you can properly log and handle the exception as you need to.
0
from decimal import *

def ask():
    input_str = input("Please enter the price of your item");
    try:
        number = Decimal( imput_str )
        return number
    except( InvalidOperation, ValueError, TypeError ) as e:
        return ask()


number = ask()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.