Search code examples
pythonpython-3.xreturn-valuenameerrorcaesar-cipher

NameErorr name 'filename' not defined after returning 'filename' from another function


Hi I was writing a code for a simple Caesar cipher decrypting program with python 3 and I got this error message when I was trying to run the program. Here's the code and I've got some description of the situation I'm having after the code.

def main():


        def getInputFile():
                """get the name of the file user wants to decrypt and check 
                if its extension is txt or not and return the file name"""
                filename = input('Enter the input file name: ')

                while not filename.endswith('.txt'): 
                        filename = input('Invalid file name extension. Please re-enter the input file name: ')

                return filename

        def decrypt(filename):
                """open the secret message and decrypt the caesar cipher and 
                return original message"""
                readSecretMessage = open(filename, "r")
                lines = readSecretMessage.readline()
                cipher_key = int(lines[0])
                secret_message = lines[1]
                decrypted = ""

                for letter in secret_message:
                        if letter in alphabet:
                                # decrypting
                                letter_index = (alphabet.find(letter) - cipher_key) % 26
                                decrypted = decrypted + alphabet[letter_index]
                        else:
                                decrypted = decrypted + letter

                return decrypted

        getInputFile()
        message_decrypted = decrypt(filename)
        print('The decrypted message is: ')
        print(message_decrypted)


main()

And I get this error message from the fourth last line when I try to run the decrypt function. I thought it's all good since I returned 'filename' value from the getInputFile function but I guess not. Can someone help me figure out why this doesn't work and how should I fix this?

Thanks for your time!


Solution

  • Returning a variable called filename from the function does not automatically create a variable called filename in the scope that the function was called in. You need to explicitly assign the returned value to a variable:

    f_name = getInputFile()
    message_decrypted = decrypt(f_name)