I'm a beginner in python and taking a course on it. I've been tasked with making a caesar cipher where I can input the alphabet used. For this I can't use ord()
or list()
or any imported functions, only basic python. I've got it to work for one letter but I can't seem to figure out how to make it work for more than one letter. Any help would be greatly appreciated!
def cypher(target, alphabet, shift):
for index in range( len(alphabet)):
if alphabet[index] == target:
x = index + shift
y = x % len(alphabet)
return (alphabet[y])
I see this is your first question. Thanks for asking.
I think what you want your code to encrypt a full length script using the function you built above. So, what your function does is it takes a letter as target
and shifts it.
This can easily be applied to a string
by iterating over its elements.
I have provided the correct implementation for your query with some tweaks here :
alphabet = "abcdefghijklmnopqrstuvwxyz"
def cypher(target, shift):
for index in range(len(alphabet)):
if alphabet[index] == target:
x = index + shift
y = x % len(alphabet)
return (alphabet[y])
string = "i am joe biden"
shift = 3 # Suppose we want to shift it for 3
encrypted_string = ''
for x in string:
if x == ' ':
encrypted_string += ' '
else:
encrypted_string += cypher(x, shift)
print(encrypted_string)
shift = -shift # Reverse the cypher
decrypted_string = ''
for x in encrypted_string:
if x == ' ':
decrypted_string += ' '
else:
decrypted_string += cypher(x, shift)
print(decrypted_string)