简体   繁体   中英

Why am I getting an UnboundLocalError: local variable 'last_move' referenced before assignment for my rock paper scissors code?

This code is for a class that I am in, where I am trying to beat other people at rock paper scissors. I keep getting the UnboundLocalError: local variable 'last_move' referenced before assignment error for my code, and I want to fix it. Thanks!

strategy_name = 'FakeOut'

def move(my_history, their_history):
    if len(their_history)==0 and len(my_history)==0:
        my_move = 'r'
    else:
        prediction = predict_they_will_repeat(their_history.lower())
        last_move = my_last_move(my_history.lower())
        my_move = beat_prediction(prediction)
    return my_move, last_move
    
def predict_they_will_repeat(their_history):
    return their_history[-1]
def my_last_move(my_history):
    return my_history[-1]
        
def beat_prediction(prediction):
    if prediction =='r' and last_move == 'p':
        winning_move = 'r'
    elif prediction == 'p' and last_move == 's':
        winning_move = 'p'
    elif prediction == 's' and last_move == 'r':
        winning_move = 's'
    elif prediction == 'r' and last_move != 'p':
      winning_move = random.choice(["r", "p", "s"])
    elif prediction == 'p' and last_move != 's':
      winning_move = random.choice(["r", "p", "s"])
    elif prediction == 's' and last_move != 'r':
      winning_move = random.choice(["r", "p", "s"])
    else:
        winning_move = '' 
        print ('Error in beat_prediction(): prediction was not r, p, or s.')
    return winning_move

last_move is only in the else block, if you don't hit the else block, it won't get assigned a value when you attempt to return it.

Try setting last_move outside of the if/else block to a default value.

def move(my_history, their_history):

    last_move = ''

    if len(their_history)==0 and len(my_history)==0:
        my_move = 'r'
    else:
        prediction = predict_they_will_repeat(their_history.lower())
        last_move = my_last_move(my_history.lower())
        my_move = beat_prediction(prediction)
    return my_move, last_move

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM