Shilo
Shilo

Reputation: 313

checking if character is in string Python

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.

Upvotes: 0

Views: 878

Answers (2)

sarveshseri
sarveshseri

Reputation: 13985

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

Upvotes: 0

Ryan O&#39;Donnell
Ryan O&#39;Donnell

Reputation: 617

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/

Upvotes: 1

Related Questions