0
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n") text = input("Type your message:\n").lower() shift = int(input("Type the shift number:\n")) def caesar(direction, text, shift): cipher_text = "" for letter in text: if direction == "encode": position = alphabet.index(letter) new_position += position elif direction == "decode": position = alphabet.index(letter) new_position -= position cipher_text += alphabet[new_position] print(cipher_text) caesar(direction, text, shift) 

UnboundLocalError: local variable 'new_position' referenced before assignment been trying to understand the concept of global variables but just can't figure out why there's an error occur in this code anyone know why and how please?

3
  • The first appearance of new_position is the line new_position += position, it was not assigned a value before that. That's illegal in Python. Commented Jun 15, 2021 at 1:59
  • You never defined new_position. A a+=1 means a=a+a. Define new_position before the loop Commented Jun 15, 2021 at 1:59
  • And can you explain what is shift for Commented Jun 15, 2021 at 2:29

3 Answers 3

0

You need to initialize new_position prior to the loop.

Sign up to request clarification or add additional context in comments.

Comments

0

You never set new_position before trying to add/subtract from it. Just add a line before the loop, like this: new_position = 0.

Comments

0

The problem is from the first new_position += position, you need write a new_position = 0 before that.

Because new_position += position means new_position = position + new_position, you need give an intial value for new_position befor you use it

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.