views:

88

answers:

3

i want to change the value of a variable within a for loop, but then have the new preserved variable changed when the loop finishes

my attempt (kinda simplified from what i'm actually doing)

SNP is a list and compar_1 is a list of lists

line_1 = empty_row
for SNP1 in compar_1:
    global line_1
    if SNP[3] == SNP1[3] 
        compare_line_1 = SNP1 
print = line_1
output_file.write(to_print)

if it finds a match within the loop i want it to change the variable to that so that's what's printed, if it doesn't find a match in the for loop i want it to print the "empty_row" (a string defined earlier)

A: 

for loops do not affect variable scope in Python (like they could in C)

If you were using variables inside a function, you can use global [var] to declare that when you refer to [var] that you mean the global one.

This is a decent overview of scope in Python

Nick T
see other comment re scope, and thanksi was thinking maybe it would get re-defined in subsequent iterations, but if it only changes when that if condition is met it shouldn't be affected by subsequent iteration at all...
Bec
+1  A: 

If you had tried to just change the variable, you would have seen that it just works. Python does not have separate scope for loops.

Daniel Roseman
ah... i was wondering about that a while ago and couldn't find a definitive answer so i've been running on the opposite assumption, i'll take it out and test it, thanks.
Bec
A: 
for SNP1 in compar_1:
    if SNP[3] == SNP1[3]:
        line_1 = SNP1 
        break
else:
    line_1 = empty_row
to_print = line_1
output_file.write(to_print)
Tendayi Mawushe
that looks more elegant than mine, but doesn't the else need to be in line with the if? it looks a bit odd.
Bec
The `else` belongs to the `for`, not the `if`. If the loop does not do at least one iteration, the `else` block is executed.
kindall
yeah i wondered if that could be it, but couldn't work out how a for could have an else, does it relate to the break?
Bec
It does indeed relate to the break, essentially the else of a for loop is executed if the loop terminates naturally (that is not by a break). So in your example if the expression "if SNP[3] == SNP1[3]" never evaluates to true the else will be executed.
Tendayi Mawushe