Question

I was wondering if i could use a subroutine here instead if so how do i or is there a another way to shorten this piece of code.

    if currency1=='GBP':
        if currency2=='USD':
            number=float(1.64)
        elif currency2=='EUR':
            number=float(1.20552)
        elif currency2=='JPY':
            number=float(171.181)
Was it helpful?

Solution

You could certainly make a dictionary:

currencies = {}
currencies['USD'] = 1.64
currencies['EUR'] = 1.20552
currencies['JPY'] = 171.181
currencies['GBP'] = 1.

number = currencies[currency2]

what's great about this is you can also do:

other_number = currencies[currency1]
exchange_rate = number / other_number # exchange rate BETWEEN the two currencies

OTHER TIPS

How about:

Brit_converter: {'USD':1.64, 'EUR':1.20552}

if currency1=='GBP':
  multiplier = converter[currency2]

or, assuming this does what I expect:

converted_currency = currency1 * converter[currency2]

Subroutines - in Python the accepted term is function - cannot replace if operator for a very simple reason - they serve different purpose:

  • Functions are used to break down code into small, manageable units and consolidate functionality required in more than one place
  • if operator changes the control flow

As it was pointed out above, dictionary is one of excellent solutions to multiple fixed choices.

I would use a dictionary like so*:

if currency1 == 'GBP':
    number = {'USD':1.64, 'EUR':1.20552, 'JPY':171.181}.get(currency2, 1)

Also, notice that I used dict.get here. If currency2 is not found in the dictionary, number will be assigned to 1 and a KeyError will not be raised. However, you can choose anything you want for the default value (or omit it entirely and have None be the default).

Finally, you should note that putting float literals inside the float built-in is unnecessary.


*Note: If you plan to use the dictionary in multiple places, don't keep recreating it. Instead, save it in a variable like so:

my_dict = {'USD':1.64, 'EUR':1.20552, 'JPY':171.181}
if currency1 == 'GBP':
    number = my_dict.get(currency2, 1)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top