Python编写一个程序可以接受人民币或英镑收入转化为英镑或人民币输出。
时间: 2024-12-19 13:16:33 浏览: 9
在Python中,你可以创建一个货币转换函数,使用实时汇率API来获取转换率。这里假设你使用了`forex-python`库来进行汇率查询。以下是一个简单的示例:
```python
from forex_python.converter import CurrencyRates
# 创建汇率实例
currencies = CurrencyRates()
def convert_currency(amount, from_currency, to_currency):
# 检查输入货币是否有效
if from_currency not in ("CNY", "GBP") or to_currency not in ("CNY", "GBP"):
raise ValueError("无效的货币类型")
# 获取当前汇率
current_rate = currencies.get_rate(from_currency, to_currency)
if current_rate is None:
print(f"无法找到{from_currency}到{to_currency}的实时汇率")
return
converted_amount = amount * current_rate
return converted_amount
# 测试转换
try:
amount = float(input("请输入金额: "))
from_currency = input("请输入原始货币(CNY或GBP): ")
to_currency = input("请输入目标货币(CNY或GBP): ")
converted_amount = convert_currency(amount, from_currency, to_currency)
print(f"{amount} {from_currency} 转换成 {to_currency} 是: {converted_amount}")
except ValueError as e:
print(e)
阅读全文