此函数将以字符串作为输入。该字符串具有以下属性:
您的函数会将字符串转换为浮点数。您不能使用任何内置命令,如int或float。您必须通过分析文本字符串中的字符来解决此问题。
如果输入无效,则返回-1作为函数的结果。
如果我输入以下内容:
100.00
200
98.78
$1,009.78
Goat
exit
这是输出的样子:
Determine Price with Tax.
Enter 'exit' at any time to quit.
Enter Amount ($X,XXX.XX):
Amount: 100.0
Tax: 6.0
Price w/ Tax: 106.0
Enter Amount ($X,XXX.XX):
Amount: 200
Tax: 12.0
Price w/ Tax: 212.0
Enter Amount ($X,XXX.XX):
Amount: 98.78
Tax: 5.93
Price w/ Tax: 104.71
Enter Amount ($X,XXX.XX):
Amount: 1009.78
Tax: 60.59
Price w/ Tax: 1070.37
Enter Amount ($X,XXX.XX):
Amount: -1
Tax: -0.06
Price w/ Tax: -1.06
Enter Amount ($X,XXX.XX):
我的代码是:
def price_to_int(text):
res = 0
valid = "$,.1234567890"
for l in text:
if l in valid:
res = float(text)
else:
return -1
return res
#---------You may not make any changes below this line-----------
print("Determine Price with Tax.")
print("Enter 'exit' at any time to quit.")
word = input("Enter Amount ($X,XXX.XX):\n")
while word.lower() != "exit":
d = price_to_int(word)
tax = 0.06
print("Amount:",round(d,2))
print("Tax:",round(d*tax,2))
print("Price w/ Tax:",round(d+d*tax,2))
word = input("Enter Amount ($X,XXX.XX):\n")
唯一错误的是功能定义。我的代码一直运行,直到我输入$ 1009.78'。我被特别要求只重写函数定义而不是改变其他任何东西。