from forex_python.converter import CurrencyRates # 创建 CurrencyRates 对象 c = CurrencyRates() # 循环转换货币 while True: # 输入金额和货币类型 amount = float(input("请输入金额:")) from_currency = input("请输入原货币类型:").upper() to_currency = input("请输入目标货币类型:").upper() # 转换货币 try: converted_amount = c.convert(from_currency, to_currency, amount) print(f"{amount} {from_currency} = {converted_amount} {to_currency}") except: print("货币转换失败!") # 询问是否继续转换 choice = input("是否继续转换?(Y/N)") if choice.lower() != "y": break 改长这个代码
时间: 2024-03-01 19:53:49 浏览: 108
以下是修改后的代码:
```python
from forex_python.converter import CurrencyRates
def currency_converter():
# 创建 CurrencyRates 对象
c = CurrencyRates()
while True:
# 输入金额和货币类型
amount = float(input("请输入金额:"))
from_currency = input("请输入原货币类型:").upper()
to_currency = input("请输入目标货币类型:").upper()
# 转换货币
try:
converted_amount = c.convert(from_currency, to_currency, amount)
print(f"{amount} {from_currency} = {converted_amount} {to_currency}")
except:
print("货币转换失败!")
# 询问是否继续转换
choice = input("是否继续转换?(Y/N)")
if choice.lower() != "y":
break
```
这里将原来的代码封装在一个函数 `currency_converter()` 中,使得代码更加整洁和易读。
阅读全文