I am following an online course for python, and we are currently working on the caesar cipher. I have seen many questions answered on the topic on this site, but non that have the caveat of having to have to previous functions used, such as in my code. The first two functions work fine when i have tested them with multiple inputs, but when I add the last function, encrypt, I get a value error of substring not found. I am lost on what I should be doing for this last part. Does anyone have suggestions that will nudge me in the right direction?
def alphabet_position(letter):
alphabet ="abcdefghijklmnopqrstuvwxyz" #Lists alphabet for a key
lower_letter = letter.lower() #Makes any input lowercase.
return alphabet.index(lower_letter) #Returns the position of input as a number.
def rotate_character(char, rot):
alphabet = "abcdefghijklmnopqrstuvwxyz"
if char.isalpha():
a = alphabet_position(char)
a = (a + rot) % 26 #needs modulo
a = (alphabet[a])
if char.isupper():
a = a.title()
return a
else:
return char
def encrypt(text, rot):
list1 = ""
for char in text:
list1 += rotate_character(text, rot)
return list1
def main():
x = input("Type a message: ")
y = int(input("Rotate by: "))
#result = rotate_character(x, y) #Not needed once encrypt function works.
result = encrypt(x, y)
print (result)
if __name__ == '__main__':
main()
You want to rotate each single character individually, but you're passing the complete text to the rotation function.
Instead use:
def encrypt(text, rot):
list1 = ""
for char in text:
list1 += rotate_character(char, rot) # "char", not "text"
return list1