1
for i in rates:
    if input_currency == currency:
        if output_currency in rates[currency]:
            pass 
        else:
            for i in rates:

Is it generally a bad thing to use the same variable i again within a for loop? Even if I loop through the same data structure again? PyCharm just tells me it's been used already, but it still works.

3
  • It's not a problem as long as you use it only as a counter in the for statements Commented Dec 2, 2019 at 15:59
  • 1
    i should only be used to note an index, if at all, give yourself a real variable name, having said that, why do you need to iterate over the same object? Commented Dec 2, 2019 at 16:00
  • Don't do this. Use j and then k. Commented Dec 2, 2019 at 17:21

1 Answer 1

2

It's not wrong. But it's dangerous if you don't know what you are doing. For example, you might have problems if you want to use i inside the outer loop:

rates = [1,2,3,4,5]
for i in rates:
    for i in rates:
        pass
    print(i) # This always prints 5

This may confuse you if you're not familiar with Python. In C, for example, a variable defined inside the inner loop is different from the one that is defined in the outer loop (i.e., you can reuse the same name for different variables).

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

1 Comment

Should also point out that this works as you would expect if you move the print statement above the inner loop

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.