Python实现简单的货币兑换程序
发布时间:2023-12-04 10:39:54
import requests
def currency_converter(amount, from_currency, to_currency):
# 使用API获取汇率数据
url = f"https://api.exchangerate-api.com/v4/latest/{from_currency}"
response = requests.get(url)
data = response.json()
# 计算兑换后的金额
exchange_rate = data['rates'][to_currency]
converted_amount = amount * exchange_rate
return converted_amount
# 使用例子
amount = 100
from_currency = 'USD'
to_currency = 'CNY'
converted_amount = currency_converter(amount, from_currency, to_currency)
print(f"{amount} {from_currency} 兑换成 {converted_amount} {to_currency}")
