Search code examples
pythonif-statementsubroutine

using subroutines in python instead of if statements


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)

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