-3

I am encountering issues in python with the if function in an exercise for my computer programming class in college, and am running into a problem with the 2nd if statement in the following program. It says that there is a syntax error:

myPlaintext = input("enter plaintext: ")

distance = int(input("enter distance: ")) def caesar(myPlaintext , distance):

for ch in myPlaintext:
    cipherText = ''
    if ch.isalpha():
        stayinAlphabet = ord(ch) + distance
        if stayinAlphabet <= 146:
            stayinAlphabet -= 26
        else:
            stayinAlphabet = (stayinAlphabet-121)%26+97
        final_letter = chr(stayinAlphabet)
    cipherText += final_letter

    print (cipherText)
return (cipherText)

caesar(myPlaintext, distance)

caesar(my_text , distance)

Here is m new function, I have fixed the errors. The function works when I use any letters as input, however, when I enter a space, the error comes up on the line that reads "cipherText += final_letter" and says that final_letter is referenced before assignment. As always, thanks for the help!!

The assignment is to write a code for using the caesar cipher to encrypt messages. Thanks, and please let me know if there are an other mistakes, as I am new to python and am prone to making mistakes

1 Answers1

1

Your indentation is inconsistent. Note where the function starts, then take note of where the function body starts. Everything below that function (except for the last) needs to be indented 4 spaces to the right. So this:

def caesar(my_text , distance):
    for ch in my_text:
        if ch.isalpha():
            alphabet = ord(ch) + distance
            if alphabet < 26:
                alphabet -=26
            else:
                alphabet = (alphabet)%26
            final_letter = chr(alphabet)
        ciphertext = ""
        ciphertext += final_letter
        print (("cipher text is: ") , ciphertext)
    return (ciphertext)

Edit: Also the colon after the function declaration is missing, and a closing bracket for the print statement.

smac89
  • 39,374
  • 15
  • 132
  • 179