Encrypt- Decrypt
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n").lower()
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
#TODO-1: Create a function called 'encrypt' that takes the 'text' and 'shift' as inputs.
#TODO-2: Inside the 'encrypt' function, shift each letter of the 'text' forwards in the alphabet by the shift amount and print the encrypted text.
#e.g.
#plain_text = "hello"
#shift = 5
#cipher_text = "mjqqt"
#print output: "The encoded text is mjqqt"
##HINT: How do you get the index of an item in a list:
#https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-in-a-list
##🐛Bug alert: What happens if you try to encode the word 'civilization'?🐛
#TODO-3: Call the encrypt function and pass in the user inputs. You should be able to test the code and encrypt a message.
def encrypt(text,shift):
res=""
shift=shift%26
for i in range (len(text)):
if ord(text[i])+shift<=ord('z'):
b=ord(text[i])+shift
print(text[i])
res+=chr(b)
else:
b=ord('a')+ord(text[i])+shift-ord('z')-1
print(text[i])
res+=chr(b)
return res
encrypted=encrypt(text,shift)
def decrypt(text,shift):
res=""
shift=shift%26
for i in range (len(text)):
if ord(text[i])-shift>=ord('a'):
b=ord(text[i])-shift
print(text[i])
res+=chr(b)
else:
b=ord('z')+ord(text[i])-shift-ord('a')+1
print(text[i])
res+=chr(b)
return res
print(encrypt(text,shift))
print(decrypt(encrypted,shift))
Comments
Post a Comment