用Python写汇率兑换
时间: 2024-09-30 18:08:30 浏览: 45
在Python中编写一个简单的汇率兑换程序,你可以使用内置的数据结构如字典来存储不同货币对的汇率,然后通过用户输入的货币和金额来进行转换。这里是一个基础示例:
```python
class CurrencyConverter:
# 假设我们有一些默认的汇率
exchange_rates = {
'USD': 6.5, # 美元兑人民币汇率
'EUR': 7.8, # 欧元兑人民币汇率
# 添加更多货币对...
}
def convert(self, from_currency, to_currency, amount):
if from_currency == to_currency:
return f"{amount} {from_currency}无需转换"
elif from_currency not in self.exchange_rates or to_currency not in self.exchange_rates:
return "无法找到该货币对的汇率"
conversion_rate = self.exchange_rates[from_currency] / self.exchange_rates[to_currency]
converted_amount = amount * conversion_rate
return f"{amount} {from_currency} = {converted_amount:.2f} {to_currency}"
# 使用示例
cc = CurrencyConverter()
input_amount = float(input("请输入需要兑换的金额:"))
from_currency = input("请输入原始货币(例如 USD、EUR):")
to_currency = input("请输入目标货币:")
result = cc.convert(from_currency, to_currency, input_amount)
print(result)
```
阅读全文