python - 我不明白这行代码。你能说我的逻辑吗?
问题描述
它关于加密
def encrypt(plain_text, shift_amount):
cipher_text = ""
for letter in plain_text:
position = alphabet.index(letter)
new_position = position + shift_amount
new_letter = alphabet[new_position]
cipher_text += new_letter
print(f"The encoded text is {cipher_text}")
我不明白 的逻辑def encrypt
。谢谢你。我是 Python 新手。示例 我不明白我们为什么要创建cipher_text
或为什么要编写position
.
我没有把代码的开始和延续。
解决方案
完整的代码可能看起来像这样带有字母列表,并且是实现Caesar Cipher的简单函数。我已经评论了下面的完整代码,以解释每一行试图做什么:
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] # list of letters
def encrypt(plain_text, shift_amount):
cipher_text = "" # setup a blank string
for letter in plain_text: # for each letter in the word you want to encode
position = alphabet.index(letter) # check the numeric position of that letter in the alphabet starting from 0 i.e. a = 0, z = 25 as it starts from 0 not 1
new_position = position + shift_amount # the position is then added to the shift_amount which is called a Caesar cypher https://en.wikipedia.org/wiki/Caesar_cipher
new_letter = alphabet[new_position] # use this new 'index' number to get the new character
cipher_text += new_letter # add that new letter to the string and then return to the beginning to get the next letter
print(f"The encoded text is {cipher_text}") # print out the newly "shifted" or encrypted word
encrypt("hello", 1)
# The encoded text is ifmmp
推荐阅读
- java - Android 应用程序无法连接到服务器
- reactjs - Uncaught Invariant Violation:使用 arrayMove 时在调度之间检测到状态突变
- python - 如何正确使用调度程序中的 enterabs
- sql - 从最小值到当前月份的运行总计
- mysql - 苹果 m1 上的 Django orm
- docker - sudo:找不到命令| gitlab-ci
- python-3.x - Unable to plot bubble plot with right size
- reactjs - 如何在 React Native 中的自定义视图上将道具传递给 StyleSheet?
- c++ - 跨平台库究竟如何适用于不同的机器
- python - How to do Categorical in pandas