Caesar Cipher encryption in Python

Viewed 405

Hi I'm trying to encrypt some text using Caesar Cipher Function in python but the error says ciphertext is not defined.

alphabet="abcdefghijklmnopqrstuvwxyz"
def encrypt(plaintext):
    ciphertext=""
    for i in range(0, len(plaintext)):
       for j in range(0, len(alphabet)):
           if plaintext[i]==alphabet[j]:
              ciphertext+=alphabet[(j+3)%26]
print("Encrypted Message:", ciphertext)
2 Answers

You just need to move it forward an indentation to be in the function

def encrypt(plaintext):
    ciphertext = ""
    for i in range(0, len(plaintext)):
        for j in range(0, len(alphabet)):
            if plaintext[i] == alphabet[j]:
                ciphertext += alphabet[(j+3) % 26]
    print("Encrypted Message:", ciphertext)

Or you could return the value and print it:

def encrypt(plaintext):
    ciphertext = ""
    for i in range(0, len(plaintext)):
        for j in range(0, len(alphabet)):
            if plaintext[i] == alphabet[j]:
                ciphertext += alphabet[(j+3) % 26]
    return "Encrypted Message: " + ciphertext


print(encrypt("xyza"))

so there is actually nothing wrong with the code. try calling the function with a string as the argument. for example:

encrypt("CSE1202")

so there is actually nothing wrong with the code. try calling the function with a string as the argument. for example:

encrypt("CSE1202")

naturally you can replace CSE1202 with anything else and it'll work

#btw if you haven't gotten the hint already, im a fellow classmate

Related