I’m trying to add a loop within the function to run 30 times and add 1 offset during each iteration.
alphabet = “abcdefghijklmnopqrstuvwxyz”
punctuation = ".,?'! "
message = “”
offset = 0
def ceaser_decode(message):
for attempts in range(0,30):
message_decoded = “”
for letter in message:
if not letter in punctuation:
letter_value = alphabet.find(letter)
message_decoded += alphabet[(letter_value + offset) % 26]
else:
message_decoded += letter
offset += 1
Get the following error when I try to call the function:
UnboundLocalError: cannot access local variable ‘offset’ where it is not associated with a value.
Can anyone help me debug, thought global variables could be accessed anywhere?
if you’re trying to change offset (which is a global variable since its declared outside all functions, classes, etc.)
inside a function, then you’d need to use the global statement [for that variable] in the function before the variable is changed,
so,
put global offset
before offset += 1
in the function.
scope for a variable can take some work to understand.
x = 5
def increase_x():
global x
x += 1
increase_x()
print(x)
Also, to keep your code’s formatting (such as indents), please use the </> button and put your code on lines between the ``` and ```
This would make your Python code easier to read [or run].
In Python, if you want to modify a global variable within a function, you need to declare it as global within the function scope using the global keyword. Try adding global offset at the beginning of your function ceaser_decode(message) to resolve the issue. This tells Python that offset refers to the global variable defined outside the function. Here’s how you can modify your function:
alphabet = "abcdefghijklmnopqrstuvwxyz"
punctuation = ".,?'! "
message = ""
offset = 0
def ceaser_decode(message):
global offset
for attempts in range(0, 30):
message_decoded = ""
for letter in message:
if letter not in punctuation:
letter_value = alphabet.find(letter)
message_decoded += alphabet[(letter_value + offset) % 26]
else:
message_decoded += letter
offset += 1
By adding global offset within your function, you should be able to access and modify the global variable offset within the loop without encountering the UnboundLocalError.
Although declaring it as a global variable fixes it, I’ve read that it’s not a good practice, ideally you have that type of variable contained within the function (local).