perofrming caesarcipher for a string using shift

Question:

from string import ascii_lowercase as alphabet1
from string import ascii_uppercase as alphabet2

import letter as letter



def cipher(user_input, shift):
    cipher1 = {char: alphabet1[(i + shift) % 26] for i, char in enumerate(alphabet1)}
    cipher2 = {char: alphabet2[(i + shift) % 26] for i, char in enumerate(alphabet2)}
    
    caesar_cipher = ""
    
    for letter in user_input:
        caesar_cipher += cipher1.get(letter, letter)
    else:
        caesar_cipher += cipher2.get(letter, letter)
    return caesar_cipher


if __name__ == "__main__":
    
    user_input = input("Enter the String: ")
    
    shift = int(input("Enter shift: "))
    
    print("Caesar Cipher: " + cipher(user_input, shift))

I am performing Caeser cipher for both upper case and lower case characters.
But the result is not correct.
cipher1 is for lowercase and cipher 2 is for upper case. I have defined it in a function. And called it in main method
the result obtained for lower case is:

Enter the String: abc
Enter shift: 2
Caesar Cipher: cdec

it should be cde

The result obtained for upper case is:

Enter the String: ABC
Enter shift: 2
Caesar Cipher: ABCE

It should be CDE

Asked By: Jyoti

||

Answers:

Check whether each letter is upper or lower case then use the corresponding cipher.

    ...
    
    for letter in user_input:
        cipher = cipher1 if letter in cipher1 else cipher2
        print(cipher[letter])

c
D
e

When the iterator is exhausted, the suite in the else clause, if present, is executed, and the loop terminates.

Your else clause was always executing.


For loop

Answered By: wwii
from string import ascii_lowercase as alphabet1
from string import ascii_uppercase as alphabet2

import letter as letter



def cipher(user_input, shift):
    cipher1 = {char: alphabet1[(i + shift) % 26] for i, char in enumerate(alphabet1)}
    cipher2 = {char: alphabet2[(i + shift) % 26] for i, char in enumerate(alphabet2)}
    
    caesar_cipher = ""
    
    for letter in user_input:
        caesar_cipher += cipher1.get(letter, letter)
    else:
        caesar_cipher += cipher2.get(letter, letter)
    return caesar_cipher


if __name__ == "__main__":
    
    user_input = input("Enter the String: ")
    
    shift = int(input("Enter shift: "))
    
    print("Caesar Cipher: " + cipher(user_input, shift))
Answered By: Rishu Tiwari
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.