如何使用函数(def)消除冗余?

2024-10-02 18:17:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个货币转换器,我已经基本完成了这个程序。然而,我试图通过实现一个函数或一个define块来消除冗余。我试过很多方法,但似乎都不管用

我当前的代码如下:

EUR = 0.83

EGY = 16.22

def currency_converter():
  money = total_value
  new_value = 0
  if currency == 1:
    new_value = money*EUR_CON
    print("Your total is " + "$" + str(money) + " US Dollars  which is " + "e£ " + str(new_value) + " European Euros.")
  elif currency == 2:
    new_value = money*EGY_CON
    print("Your total is " + "$" + str(money) + " US Dollars  which is " + "e£ " + str(new_value) + " Egyptian Pounds.")

我想本质上使if/elif块下的子句成为一个函数。我试过这样做:

def conversion(EUR_CON,GDP_CON, BRL_CON, EGY_CON, YEN_CON):
  new_value = money*conversion()
  print("Your total is " + "$" + str(money) + " US Dollars  which is " + str(new_value)+ str(conversion)

if currency == 1:
    conversion(EURO_CON)

但它不起作用。有人能帮忙吗


Tags: newyourifisvalueeurconcurrency
2条回答

将所有转换率放入列表或字典中,这样就不需要所有那些if语句

函数不需要太多参数。只是你要兑换的货币和金额。然后,该函数可以查找与currency参数相关的所有信息

conversion_data = {
    'EUR': {'rate': 0.83, 'symbol': '€', 'name': 'European Euros'},
    'EGY': {'rate': 16.22, 'symbol': '£', 'name': 'Egyptian Pounds'},
    ...
}

def conversion(currency, dollars):
    new_value = dollars * conversion_data[currency]['rate']
    return f"Your total is ${dollars} US dollars which is {conversion_data[currency]['symbol']}{new_value} {conversion_data[currency]['name']}."

print(conversion('EUR', 5))

正确的方法是制作一个映射或enum,将转换类型与相关参数(在本例中是目标货币的乘数和字符串名称)联系起来。例如,使用enum

from enum import Enum

class Currency(Enum):
    EUR = 0.83, "European Euros"
    EGY = 16.22, "Egyptian Pounds"

def currency_converter(target_currency):
    multiplier, name = target_currency.value  # Retrieve value of enum and unpack parts for use
    new_value = money * multiplier
    print(f"Your total is ${money} US Dollars which is {new_value} {name}")

这样,您就可以使用它,只需:

currency_converter(Currency.EUR)  # Convert to euros

需要明确的是:将dict用于类似的目的也非常好。枚举主要只是强调存在一组固定的、已知的可能转换,其中dict并没有充分地考虑到这一点(添加和删除键始终是可能的)

我将注意到,在实际代码中,函数通常不应该依赖于从全局函数接收非常量信息,也不应该依赖于print结果(return调用它们允许调用方print,或者不依赖于print,如它们所选择),因此更好的设计应该是:

def convert_usd_to_currency(target_currency, money):
    multiplier, _ = target_currency.value  # Retrieve value of enum and unpack parts for use
    return money * multiplier

可能有一个执行print操作的助手(如果您确实有许多地方需要以相同的方式对其进行格式化):

def print_converted_currency(currency, money):
    new_value = convert_usd_to_currency(currency, money)
    print(f"Your total is ${money} US Dollars which is {new_value} {currency.name}")

我承认我在这里缺乏想象力;我几乎从来没有看到需要考虑输出代码本身(每个位置根据需要打印不同的内容),因此我可能只会将工作内联到一个实际执行转换的位置(而不是可能需要执行转换的多个位置)

相关问题 更多 >