具有先决条件函数的凯撒密码
Caesar cipher with prerequisite functions
我正在学习 python 的在线课程,我们目前正在研究凯撒密码。我在这个网站上看到过很多关于这个主题的问题,但没有一个必须必须使用以前的函数,比如在我的代码中。当我用多个输入测试它们时,前两个函数工作正常,但是当我添加最后一个函数时,加密,我得到一个未找到子字符串的值错误。我不知道我应该为最后一部分做什么。有没有人有建议可以帮助我朝着正确的方向前进?
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()
您想单独旋转每个字符,但您要将完整的文本传递给旋转函数。
改为使用:
def encrypt(text, rot):
list1 = ""
for char in text:
list1 += rotate_character(char, rot) # "char", not "text"
return list1
我正在学习 python 的在线课程,我们目前正在研究凯撒密码。我在这个网站上看到过很多关于这个主题的问题,但没有一个必须必须使用以前的函数,比如在我的代码中。当我用多个输入测试它们时,前两个函数工作正常,但是当我添加最后一个函数时,加密,我得到一个未找到子字符串的值错误。我不知道我应该为最后一部分做什么。有没有人有建议可以帮助我朝着正确的方向前进?
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()
您想单独旋转每个字符,但您要将完整的文本传递给旋转函数。
改为使用:
def encrypt(text, rot):
list1 = ""
for char in text:
list1 += rotate_character(char, rot) # "char", not "text"
return list1