3

I have the following error:

currency = row[0]
IndexError: list index out of range

Here is the code:

 crntAmnt = int(input("Please enter the amount of money to convert: "))
    print(currencies)
    exRtFile = open ('exchangeRate.csv','r')
    exchReader = csv.reader(exRtFile)
    crntCurrency = input("Please enter the current currency: ")
    validateloop=0
    while validateloop == 0:
        for row in exchReader:
                currency = row[0]
                if currency == crntCurrency:
                    crntRt = row[1]
                    validateloop=+1

Heres the CSV file:

Japanese Yen,169.948

US Dollar,1.67

Pound Sterling,1

Euro,5.5

Here's an input/Output example:

Please enter the amount of money to convert: 100
['Pound Sterling', 'Euro', 'US Dollar', 'Japanese Yen']
Please enter the current currency: Pound Sterling
user3165683
  • 347
  • 1
  • 9
  • 28
  • 4
    I have often found the humble `print` statement most efficacious... for example, you could use it to see what's in `row`. – kindall Apr 09 '14 at 22:10
  • as @kindall said, can you put a couple of print statements and show us what they output? Or you can show us what is in `exchangeRate.csv`... – A.J. Uppal Apr 09 '14 at 22:11
  • i do not c how that would be useful? – user3165683 Apr 09 '14 at 22:12
  • 1
    ... you don't see how it would be useful to know whether `row` has a zeroth element, or is in fact a list at all? – kindall Apr 09 '14 at 22:13

2 Answers2

3

You probably have a blank row in your csv file, causing it to produce an empty list

There are a couple solutions


1. Check if there are elements, only proceed if there are:

for row in exchReader:
    if len(row):  # can also just do   if row:
        currency = row[0]
        if currency == crntCurrency:

2. Short-circuit an and operator to make currency an empty list, which won't match crntCurrency:

for row in exchReader:
    currency = row and row[0]
    if currency == crntCurrency:
mhlester
  • 22,781
  • 10
  • 52
  • 75
2

Try printing out the row. The convention for variable names in python are like_this and not likeThis. You might find the break keyword useful:

for row in exch_reader:
    currency = row[0]
    if currency == crnt_currency:
        crnt_rt = row[1]
        break

To only index the row when the row actually contains something:

currency = row and row[0]

Here row[0] is only executed if row evaluates to True, which would be when it has at least one element.

Scorpion_God
  • 1,499
  • 10
  • 15