转换器
Coddy 货币转换器:Python 项目 课程的第 5 课,共 5 课。
让我们来创建这个项目的核心部分:转换器!
挑战
简单添加一个名为 convert 的函数,它接收来源货币、金额和目标货币,并print换算后的目标货币金额。
使用你创建的两个辅助函数 from_usd 和 to_usd。
如果遇到错误,你应该打印错误消息。可以这样做(用 try-except 包裹你的代码):
try:
# main code
except Exception as e:
print(e)查看测试用例,了解所需的输出格式。
亲手试试
CURRENCIES = {
'USD': 1,
'EUR': 1.06,
'YEN': 0.0067,
'GBP': 1.23,
'AUD': 0.64,
'CAD': 0.74
}
def to_usd(from_currency, amount):
if from_currency not in CURRENCIES:
raise Exception(f'{from_currency} is not supported')
elif amount < 0:
raise Exception(f'Invalid amount')
else:
res = CURRENCIES[from_currency] * amount
return res
def from_usd(to_currency, amount):
if to_currency not in CURRENCIES:
raise Exception(f'{to_currency} is not supported')
elif amount < 0:
raise Exception(f'Invalid amount')
else:
res = amount / CURRENCIES[to_currency]
return round(res, 4)货币转换器:Python 项目中的所有课
自己练习: Python 在线编译器