首页 > 解决方案 > 我不明白这行代码。你能说我的逻辑吗?

问题描述

它关于加密

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.

我没有把代码的开始和延续。

标签: python

解决方案


完整的代码可能看起来像这样带有字母列表,并且是实现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

推荐阅读