121k views
0 votes
Program a substitution cipher in Python. Create 2 functions one for encryption and the other for decryption ( get the text as the parameter).

1 Answer

6 votes

alphabet = "abcdefghijklmnopqrstuvwxyz"

def encrypt(txt):

shift = int(input("Enter the shift: "))

new_txt = ""

for x in txt:

if x in alphabet:

if alphabet.index(x)+shift >= len(alphabet):

new_txt += alphabet[(alphabet.index(x)+shift - len(alphabet))]

else:

new_txt += alphabet[alphabet.index(x)+shift]

else:

new_txt += x

return new_txt

def decrpyt(txt):

shift = int(input("Enter the known shift: "))

new_txt = ""

for x in txt:

if x in alphabet:

new_txt += alphabet[alphabet.index(x) - shift]

else:

new_txt += x

return new_txt

print(encrypt("yellow dog."))

print(decrpyt("lryybj qbt."))

My code works with lowercase text only. If you need me to modify the code, I can do that. I tested my code with a shift of 13 in both the encryption and decryption. I hope this helps!

User SouravA
by
5.7k points