简体   繁体   中英

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.

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/

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM