Nitsuj Felisco
Nitsuj Felisco

Reputation: 3

Python UnboundLocalError "Need help"

def rotate_word(word,number)
    for i in word:
        word_num = ord(i)
        new_word += chr(word_num + number)
return new_word

Hi guys, the code above is not working. This is a python function. When i run the program i will return an error: "UnboundLocalError: 'new_word' referenced before assignment"

what this means? Can anyone help me?

the output of my function would be:

print rotate_word('abc',5)

output: fgh

Upvotes: 0

Views: 252

Answers (1)

gak
gak

Reputation: 32793

You should define new_word before using it. Place this before the for:

new_word = ''

You are also missing an indentation for the return and a colon after the def. Here is a fixed version:

def rotate_word(word, number):
    new_word = ''
    for i in word:
        word_num = ord(i)
        new_char = chr(word_num + number)
        if new_char > 'z':
            new_char = chr(ord(new_char) - 26)
        new_word += new_char
    return new_word

print rotate_word('abc', 5)
print rotate_word('xyz', 3)

EDIT: I've updated your code so it wraps after 'z'

Upvotes: 2

Related Questions