我正在构建一个货币转换器,我已经基本完成了这个程序。然而,我试图通过实现一个函数或一个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)
但它不起作用。有人能帮忙吗
将所有转换率放入列表或字典中,这样就不需要所有那些
if
语句函数不需要太多参数。只是你要兑换的货币和金额。然后,该函数可以查找与currency参数相关的所有信息
正确的方法是制作一个映射或
enum
,将转换类型与相关参数(在本例中是目标货币的乘数和字符串名称)联系起来。例如,使用enum
:这样,您就可以使用它,只需:
需要明确的是:将
dict
用于类似的目的也非常好。枚举主要只是强调存在一组固定的、已知的可能转换,其中dict
并没有充分地考虑到这一点(添加和删除键始终是可能的)我将注意到,在实际代码中,函数通常不应该依赖于从全局函数接收非常量信息,也不应该依赖于
print
结果(return
调用它们允许调用方print
,或者不依赖于print
,如它们所选择),因此更好的设计应该是:可能有一个执行
print
操作的助手(如果您确实有许多地方需要以相同的方式对其进行格式化):我承认我在这里缺乏想象力;我几乎从来没有看到需要考虑输出代码本身(每个位置根据需要打印不同的内容),因此我可能只会将工作内联到一个实际执行转换的位置(而不是可能需要执行转换的多个位置)
相关问题 更多 >
编程相关推荐