要运行一个Python货币转换程序,你可以按照以下步骤进行:
1. 确保你已经安装了`forex-python`库。如果尚未安装,可以通过命令行使用`pip install forex-python`命令进行安装。
2. 创建一个Python脚本文件,例如`currency_converter.py`,并将以下代码粘贴到该文件中:
from forex_python.converter import CurrencyRates
def currency_converter():
c = CurrencyRates()
print("欢迎使用货币转换器!")
print("支持的货币代码: USD, EUR, GBP, JPY, INR, CNY, AUD, CAD")
source_currency = input("请输入源货币代码: ").upper()
target_currency = input("请输入目标货币代码: ").upper()
amount = float(input("请输入要兑换的金额: "))
try:
exchange_rate = c.get_rate(source_currency, target_currency)
converted_amount = amount * exchange_rate
print(f"{amount} {source_currency} 兑换成 {converted_amount:.2f} {target_currency}")
except Exception as e:
print(f"发生错误: {e}")
if __name__ == "__main__":
currency_converter()
3. 保存文件并在命令行中运行该脚本,例如:
python currency_converter.py
4. 根据提示输入源货币代码、目标货币代码和要转换的金额。
5. 程序将输出转换后的金额。
请注意,上述代码示例使用了`forex-python`库来获取实时汇率数据。如果你希望使用预先提供的汇率数据进行转换,可以手动设置汇率数据,例如:
exchange_rates = {
'USD': 1.18,
'EUR': 0.85,
'JPY': 130.35
}
def convert_currency(amount, from_currency, to_currency):
if from_currency in exchange_rates and to_currency in exchange_rates:
converted_amount = amount * exchange_rates[from_currency] / exchange_rates[to_currency]
return converted_amount
else:
return None
在这个例子中,你需要手动更新汇率数据。