7-1 jmu-python-汇率兑换
时间: 2025-07-06 19:51:06 浏览: 3
### Python 实现汇率兑换
为了实现简单的汇率兑换功能,可以编写一段Python代码来接收用户输入的金额以及目标货币,并根据预设的汇率进行转换。下面是一个基本的例子:
```python
def exchange_rate_converter(amount, from_currency, to_currency):
# 预定义一些常见货币之间的汇率
rates = {
"USD": {"CNY": 6.98, "EUR": 0.91},
"CNY": {"USD": 0.14, "EUR": 0.013},
"EUR": {"USD": 1.10, "CNY": 7.52}
}
if from_currency not in rates or to_currency not in rates[from_currency]:
raise ValueError("Unsupported currency conversion")
converted_amount = amount * rates[from_currency][to_currency]
return round(converted_amount, 2)
if __name__ == "__main__":
try:
user_input = input().strip()
parts = user_input.split()
if len(parts) != 3:
raise ValueError("Invalid input format")
amount = float(parts[0])
from_currency = parts[1].upper()
to_currency = parts[2].upper()
result = exchange_rate_converter(amount, from_currency, to_currency)
print(f"Converted Amount: {result} {to_currency}")
except Exception as e:
print(e)
```
这段代码首先定义了一个`exchange_rate_converter`函数用于处理不同货币间的转换逻辑[^1]。该函数接受三个参数:要转换的数量(`amount`)、原始货币单位(`from_currency`)和目标货币单位(`to_currency`)。
在主程序部分,通过`input()`获取用户的输入并解析成具体的数值与货币符号组合。这里假设用户按照“数量 原始货币 目标货币”的顺序提供信息。之后调用上述定义好的函数完成实际的计算工作,并输出最终的结果给用户查看[^2]。
阅读全文
相关推荐
















