Home > other >  Problem in a list with previously created variables. Error local variable 'Victory' refere
Problem in a list with previously created variables. Error local variable 'Victory' refere

Time:04-01

I have Victory, Draw, Lose variables for a hockey game. Obviously, based on the final result of a game, only one of these variables will be True. For this reason I created them inside a try and except: pass.

Now I would like to print only one of these variables (the True one, for example Victory, because Victory becomes True based on a scraping of the results of the hockey match), but I get the error UnboundLocalError: local variable 'Victory' referenced before assignment when I search to print the True variable, because Victory was already named before the assignment. Given the simplicity of the problem, I report only the part useful for the resolution:

Maybe I shouldn't use a list

#scraping and assignment of Point_Team_A and Point_Team_B
...

try:
    Victory = Point_Team_A > Point_Team_B 
    Draw = Point_Team_A == Point_Team_B
    Lose = Point_Team_A < Point_Team_B
except:
    pass

result=[Victory, Draw, Lose] #great problem is here

print (*filter(None, result), sep='\n') #and here

For example if the result is a Victory, I want to get the output: Victory

NOTE: I use try / except because only one (1) variable will be True between Victory, Draw, Lose. The two False variables will be recognized as an error, because I previously created Point_Team_A and Point_Team_B inside an if / else condition. Subsequently I use Point_Team_A and B to create the 3 variables above. For example, if the result of a hockey match is 7-3, it means that team A has won, because Victory = Point_Team_A> Point_Team_B. Consequently Draw and Lose will be recognized by Python as an error, for this use try / except.

CodePudding user response:

just do

if a_points > b_points:
    print('victory')
elif a_points == b_points:
    print('draw')
else:
    print('defeat')

your code as is, when it works, would literally only ever print True

if you want another way to reproduce this error you're seeing, try this:

def f():
    try:
        x = 1 / 0
    except ZeroDivisionError:
        pass

    print(x)

what's happening is that the python interpreter knows that the name x exists in scope but also that it's never bound to anything (because the exception occurs before the assignment). so you get UnboundLocalError

CodePudding user response:

When there is an exception in the try block the variables created in the try block will not be available in an outside try block, so create a variable and initialize it either in the outside try block or inside except

Victory = Draw = Lose = False
try:
    Victory = Point_Team_A > Point_Team_B 
    Draw = Point_Team_A == Point_Team_B
    Lose = Point_Team_A < Point_Team_B
except:
    pass

result=[Victory, Draw, Lose] 

print (*filter(None, result), sep='\n')
  • Related