0

I've had a look around at older posts on this topic but can't see how to apply the knowledge to my code,

I'm trying to turn two functions into 1 as they are very similar but while trying to execute the function I get a:
local variable 'z' referenced before assignment
error, and here is the code:

code_a = ['h','e','l','o']
code_b = ['d','t','u','x']
def encrypt(word, a):
    if a == 'encrypt':
       z = code_a
       y = code_b
    elif a == 'decrypt':
       z = code_b
       y = code_a
    newword = ''
    for char in word:
      x = 0
      found = False
      while found == False:
          if z[x] == char:
              newword = newword + y[x]
              found = True
          x += 1
    return newword
x = encrypt('hello', 'encrypt')
print(x)

any help would be greatly appreciated thanks in advance


EDIT: After messing around with my code I figured out that the problem was the uncertainty of z and 'y' so I got rid of the elif statement and swapped the values in the if statement and added an else statement to make the default what the original if statement was.

  • You really need to provide a [mcve], which includes the *calling code*. Probably, you are passing something to `a` which is neither of the strings you are checking for, thus `z` never gets assigned. – juanpa.arrivillaga Feb 02 '21 at 09:32
  • ok I'll add it now – xXdesertwolfXx Feb 02 '21 at 09:45
  • It looks to me like, within the encrypt function, the local variables code_a and code_b have not been initialized. Checkout [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) for ways to solve thisn problem – itprorh66 Feb 02 '21 at 13:45

0 Answers0