Marc M Marc M - 6 months ago 18
Python Question

Error message saying variable not defined when it is. Python

I am trying to create a simple encryption program in python using functions but am having a problem where I get an error message when I run the program saying ('msgReversed' is not defined) when it is.

the program works by first reversing the users message and then shifting the letters to the value of the Key

alphabet=("abcdefghijklmnopqrstuvwxyz ")

def userInput():
plaintext=input("Enter message to encript")
k=int(input("Enter encription Key you want to use (1-25)"))
return (k,plaintext)

def reverseMsg(plaintext):
msgReversed=''
leng=len(plaintext)-1
for c in plaintext:
msgReversed+=plaintext[leng]
leng=leng-1
print(msgReversed)
return(msgReversed)

def encript(msgReversed,k):
cipher=''
for c in msgReversed:
if c in alphabet:
cipher+=alphabet[(alphabet.index(c)+k)%(len(alphabet))]
print(cipher)

(k,plaintext)=userInput()
reverseMsg(plaintext)
(cipher)=encript(msgReversed,k)

Answer

As mentioned in my comment, your variable msgReversed is not declared outside of your function, so it is not defined when you call it outside of it. In order to avoid posting duplicate answers, here is another approach:

I do not know if you have worked with classes before, but here is an example and pythons official documentation (https://docs.python.org/2/tutorial/classes.html)

class Encrypt:

    def __init__(self):



        (k,plaintext)=self.userInput()
        self.reverseMsg(plaintext)
        cipher =self.encript(self.msgReversed,k)

    def userInput(self):
        plaintext=input("Enter message to encript")
        k=int(input("Enter encription Key you want to use (1-25)"))
        return (k,plaintext)

    def reverseMsg(self, plaintext):
        self.msgReversed=''
        leng=len(plaintext)-1
        for c in plaintext:
            self.msgReversed+=plaintext[leng]
            leng=leng-1
        print(self.msgReversed)
        return(self.msgReversed)

    def encript(slf, msgReversed, k):
        alphabet=("abcdefghijklmnopqrstuvwxyz ")
        cipher=''
        for c in msgReversed:
            if c in alphabet:
                cipher += alphabet[(alphabet.index(c)+k)%(len(alphabet))]
        print(cipher)

Encrypt()

As for Global variables, you can declare a global within a function. all you have to do is declare it global:

variable_name global

so your function with your variable msgReversed would be as follows:

def reverseMsg(plaintext):
    global msgReversed
    msgReversed = ''
    leng=len(plaintext)-1
    for c in plaintext:
        msgReversed+=plaintext[leng]
        leng=leng-1
    print(msgReversed)
    return(msgReversed)