Reputation: 83
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])
Upvotes: 2
Views: 3829
Reputation: 18826
There are many ways to accomplish such a thing, but you probably want a form of
str.maketrans
table)Here's a complete example for a very boring Caesar Cipher
source_string = input("source string: ").upper()
cut_position = int(input("rotations: "))
# available as string.ascii_uppercase
source_values = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# create a mapping
mapping = source_values[cut_position:] + source_values[:cut_position]
# display mapping
print("using mapping: {}".format(mapping))
# build a translation table
table = str.maketrans(source_values, mapping)
# use your translation table to rebuild the string
resulting_string = source_string.translate(table)
# display output
print(resulting_string)
Providing a mapping and lowercasing text is left as an exercise
Upvotes: 0
Reputation: 475
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)
Upvotes: 0