Question

I have a bit Caesar Cipher code and cant get the try/except to work. All it does is repeat up to the first input. It does not display "INCORRECT INPUT". What can I do to fix this?

while True:
    try:
        encrypt = raw_input("Would you like to encrypt or decrypt a message? (E/D) : ").lower()
        print("")
        if encrypt == 'e':
            print("ENCRYPTION: Due to the nature of the Caesar Cipher, Numbers and Symbols will 
                  be removed. Please represent numbers as the word...")
            print("I.E. - 7 should be entered as 'seven'. ")
            print("")
            sentence = raw_input("Please enter a sentence : ").lower()
            newString = ''
            validLetters = "abcdefghijklmnopqrstuvwxyz "
            space = []
            for char in sentence:
                if char in validLetters or char in space:
                    newString += char
            shift = input("Please enter your shift : ")
            resulta = []
            for ch in newString:
                x = ord(ch)
                x = x+shift
                resulta.append(chr(x if 97 <= x <= 122 else 96+x%122) if ch != ' ' else ch)
            print sentence
            print("")
            print("Your encryption is :")
            print("")
            print ''.join(resulta)
        if encrypt == 'd':
            print("DECRYPTION : PUNCTUATION WILL NOT BE DECRYPTED")
            print("")
            sentence = raw_input("Please enter an encrypted message : ").lower()
            newString = ''
            validLetters = "abcdefghijklmnopqrstuvwxyz "
            for char in sentence:
                if char in validLetters:
                newString += char
            shift = input("Please enter your shift : ")
            decryptshift = 26 - shift
            resulta = []
            for ch in newString:
                x = ord(ch)
                x = x + decryptshift
                resulta.append(chr(x if 97 <= x <= 122 else 96+x%122) if ch != ' ' else ch)
            print sentence
            print("")
            print("Your encryption is :")
            print("")
            print ''.join(resulta)
        if encrypt == 'q':
            break
    except:
        print("")
        print("INCORRECT INPUT!")
        print("")
    continue

I've tried various locations for both try and except...I am lost. Thanks in advance!

Was it helpful?

Solution

try..except blocks are used if you or the system raise an exception. The except block will not be executed if the try block finishes successfully. In your case it does, your program simply does not go into the if blocks.

To get the expected result, rewrite the if statements as follows:

    if encrypt == 'e':
        ...
    elif encrypt == 'd':
        ...
    elif encrypt == 'q':
        break
    else:
        print("")
        print("INCORRECT INPUT!")
        print("")

This way, you combine all the conditions, and have a "default" statement. The else after elifs will enter if none of the previous elifs AND the first if are entered (which is basically saying that none of the conditions are true).

If you don't use elif and use only if (as in your original code), the condition chain is broken and the else at the end will catch all cases in which encrypt != "q", even if it is "e" or "d".

OTHER TIPS

I've run your code and it seems ok, after I fixed the mismatched identation here:

      if char in validLetters:
      newString += char

to this:

      if char in validLetters:
          newString += char

I got the following output:

Please enter a sentence : test
Please enter your shift : 

INCORRECT INPUT!

this is OT from the original question , but

result = raw_input("Enter Q, D, or E")
while result.lower() not in ["q","d","e"]:
      result = raw_input("Invalid Response! Enter Q,D, or E:")
#now you know result is one of q d or e

is probably a better way to get your input

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top