[英]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:
我在檢查是否輸入了錯誤var中的一個或多個字符時遇到麻煩。
當輸入的內容不是數字時
輸出為:
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'>]
如果有角色,我想編寫一個循環,使他們有另一個機會重新輸入價格。
如果希望輸入為數字,建議將其設為浮點型,並在無法解析的情況下處理異常:
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.
不過,請注意,浮動匯率並不是准確處理資金的好方法! 這是一筆大買賣! 您需要在線搜索以找到一個好的解決方案: 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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.