Title

Thursday, 5 February 2015

Variable scope inside for and if/else


I have the following snippet of code which does not update the variable CH_end inside the if statement if else statement unless I use 2 separate if statements.

for provider, games in content_providers.iteritems():     if provider == 'Test':     for state in states:   if state == states[-1]:   CH_end = '] \n}'   else:   CH_end = '] \n},'       if state == 'STATE1':   print jsontemplate.CH_STATE1_start     for game in games:   if game == games[-1]:   print game_data + ' }'   else:   print game_data + ' },'     print CH_end       if state == 'STATE2':   print jsontemplate.CH_STATE1_start     for game in games:   if game == games[-1]:   print game_data + ' }'   else:   print game_data + ' },'     print CH_end    #more

If I change the second if block to the following it sort of works:

if state != states[-1]:   CH_end = '] \n},'  else:   CH_end = '] \n}'

with the above it executes the if but never sets the CH_end value in the else block.

Only way to get it work so far is by having 2 separate if blocks:

if state != states[-1]:   CH_end = '] \n},'    if state == states[-1]:   CH_end = '] \n}'

Granted I'm fairly new to Python, but I can't seem to make sense of this.

Answer

No comments:

Post a Comment