-1

i need to print the currency conversion. but instead of multiplying the value into 100. im gettinbg an output as the amount is repeated for 100 times

def curconv(curr,amount):
    value = 0
    c = ['AUD','CHF','CNY','DKK','EUR','GBP','HKD','INR','JPY','MXN','MYR','NOK','NZD','PHP','SEK','SGD','THB']
    cv = ['1.0345157','1.0237414','0.1550176','0.1651442','1.2296544','1.5550989','0.1270207','0.0177643','0.01241401','0.0751848','0.3145411','0.1677063','0.8003591','0.0233234','0.148269','0.788871','0.0313789']
    for i in range(len(c)):
        if c[i]== curr:
            value = (amount * cv[i])
    return value
print(curconv('INR',100))
deceze
  • 510,633
  • 85
  • 743
  • 889

1 Answers1

0

The immediate problem is that the values in the cv list are str, but they should be float. The easiest (in terms of code changes) fix would be to convert the value to float before adding, i.e. value = (amount * float(cv[i])), or better, remove all the ' in the cv list.

def curconv(curr,amount):
    value = 0
    c = ['AUD','CHF','CNY', ...]
    cv = [1.0345157,1.0237414,0.1550176, ...]
    for i in range(len(c)):
        if c[i]== curr:
            value = (amount * cv[i])
    return value

Also, note that your code may behave unexpectedly if you pass an unknown currency code; better raise an exception in that case. And using a dict instead of two lists will make the code faster and easier to maintain. (You can create that dict with dict(zip(c, cv)).)

RATES = {'AUD': 1.0345157, 'CHF': 1.0237414, 'CNY': 0.1550176,
         'DKK': 0.1651442, 'EUR': 1.2296544, 'GBP': 1.5550989,
         'HKD': 0.1270207, 'INR': 0.0177643, 'JPY': 0.01241401,
         'MXN': 0.0751848, 'MYR': 0.3145411, 'NOK': 0.1677063, 
         'NZD': 0.8003591, 'PHP': 0.0233234, 'SEK': 0.148269,  
         'SGD': 0.788871,  'THB': 0.0313789}
 
def curconv(curr, amount):
    if curr not in RATES:
        raise ValueError(f"Unknown Currency Code '{curr}'")* amount
    return RATES[curr] * amount
tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • Perhaps also add the usual sermon about float inaccuracy; probably truncate the result of the conversion to two decimals, or switch to integers units. See also https://stackoverflow.com/questions/588004/is-floating-point-math-broken – tripleee Feb 09 '21 at 13:00
  • @tripleee Thanks, but I don't really see reason for either here. In particular, different currencies may have different number of decimal places, so truncating to two decimals does not seem useful IMHO. – tobias_k Feb 09 '21 at 13:07