1

I have written a program to calll exchange rates from a file but it prints an output fo reach row, there is a logic error but i cant't find it.

import csv
exRtFile = open ('exchangeRate.csv')
exchReader = csv.reader(exRtFile)
newCurrency = raw_input("Please enter the currency you would like to convert to: ")
for row in exchReader:
        currency = row[0]
        if currency == newCurrency:
            newRt = row[1]
            print(newRt)
            break

print("Sorry, that is not a valid currency")

file:

Pound Sterling,1
Euro,1.22
US Dollar,1.67
Japanese Yen,169.948
6
  • What delimiter are you using? Default would be comma, but I don't see any commas in your file. Commented Mar 7, 2014 at 12:17
  • could you please elaborate more, like what is expected output and what actual you are getting. Commented Mar 7, 2014 at 12:18
  • CSV(Comma delimited) in excel Commented Mar 7, 2014 at 12:18
  • expecting 1.22 but getting 'Sorry, that is not a valid currency' then 1.22 Commented Mar 7, 2014 at 12:19
  • Could you please provide the exact content of the csv file, including commas? When I try to reproduce the problem, it does not print every line, but no line at all, because the lines are not split correctly. Commented Mar 7, 2014 at 12:19

2 Answers 2

2

If I understand your question correctly, the problem is that it prints the "Sorry..." line even when it finds the currency in the file. To prevent this, you can add an else to the for loop.

for row in exchReader:
    currency = row[0]
    if currency == newCurrency:
        newRt = row[1]
        print(newRt)
        break
else:
    print("Sorry, that is not a valid currency")

This way, the else block will only be executed when the loop is exited normally, i.e. without break.

Sign up to request clarification or add additional context in comments.

1 Comment

You beat me by 12 seconds! >;-]
2

You need to specify the delimiter or your csv file; to me it looks like tab-delimited, so:

exchReader = csv.reader(exRtFile, delimiter='\t')

Then you have to understand that break is only breaking out of the loop, not out of the whole program. For that you will need to use sys.exit(). But a nicer solution is the else clause for for loops:

for row in exchReader:
    currency = row[0]
    if currency == newCurrency:
        newRt = row[1]
        print(newRt)
        break
else:
    print("Sorry, that is not a valid currency")

1 Comment

Oh, you changed the tabs to commas in your question. Then use delimiter=',' of course (but that might also be the default).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.