货币兑换程序的优化

时间:2018-08-21 13:49:58

标签: python-3.x

正如标题中所述,我正在创建一个货币兑换程序

我想创建一个程序,将每种单一类型的货币都转换为另一种,但是我不确定最有效的方式

我的想法

我的最初计划是为所有货币转换创建函数,并创建在两种情况都成立时将执行该函数的if语句。但这需要我很多年...

# what currency they want to exchange
currency = input("What currency would you like to exchange: ").lower()

# what currency they want to exchange to
exchange_currency = input("What currency would you like to exchange to: ").lower

# how much they want to exchange
amount_of_currency = input("How much %s would you like to exchange: " % (currency))

# calculates pound to dollar
def pound_to_dollars(amount_of_currency):
result = float(amount_of_currency) * 1.28
print("That would be",result,exchange_currency)

# calculation takes place if both conditions are true
if currency == "pound" or "£" and exhange_currency == "dollar" or "$":
pound_to_dollars(amount_of_currency)

问题

是否有一种方法可以处理所有转换?

你们将如何有效地创建货币兑换系统?

1 个答案:

答案 0 :(得分:0)

# build a dictionary of rates
exchange_rates = {
    # MADE UP RATES
    ("USD", " EUR"): .85,
    ("BRL", "YEN"): 150,
    # Add as desired
}

def convert(original_currency, new_currency):
    # get the relevant rate from the dictionary
    rate = exchange_rates[(original_currency, new_currency)]
    # prompt user for how much he wants to exchange. 
    user_value = raw_input("How much would you like to exchange {}? ".format(original_currency))
    # explicitly define type of input
    amount = float(user_value)
    # perform conversion
    conversion = amount * rate
    print " %s %s is equal to %s %s." % (user_value, original_currency, conversion, new_currency)

如果您注意到,所有这些x_currency_to_y_currency函数都具有相似的结构,这通常表明可以使用更通用的函数来执行任务。编程中的这个概念属于术语“ DRY”(干燥)的缩写,“不要重复自己”。

此功能的示例用法如下:

convert('USD', 'EUR')

这将输出“ x USD等于y EUR”,其中x是要转换用户输入的货币量。