有人可以解释一下这个简单的python代码吗?

时间:2013-09-30 16:02:09

标签: python encryption

我进入GCSE计算几周,我在第9年。今天我们通过了一个简单的加密程序。我真的不太了解它。有经验的python程序员可以解释这段代码,简单

顺便说一句 - 我已经根据我理解的代码发表评论。

message = str(input("Enter message you want to encrypt: ")) #understand
ciphered_msg = str() #understand
i = int() #understand
j = int() #understand
n = int(3)

for i in range(n):
    for j in range(i, len(message), n):
        ciphered_msg = ciphered_msg + message[j]

print(ciphered_msg) #understand

请帮助我,因为我真的想要更多的蟒蛇知识并在考试中获得A *。

我知道for循环是如何工作的,但我只是不明白这个是如何工作的。

谢谢!

1 个答案:

答案 0 :(得分:3)

这些行是非Pythonic,你不应该这样做:

ciphered_msg = str()
i = int()
j = int()
n = int(3)

相反,这是完全等效的代码,但更简单,更清晰:

ciphered_msg = ""
i = 0 # unnecessary, the i variable gets reassigned in the loop, delete this line
j = 0 # unnecessary, the j variable gets reassigned in the loop, delete this line
n = 3

循环正在执行以下操作:从0开始,然后是1,最后是2,它接收消息长度中的每个第三个索引并访问{{{}中的相应位置1}}数组,在该位置附加字符并将结果累加到message变量中。例如,如果ciphered_msg的长度为message,则5中的索引将按此顺序访问:

message

所以基本上我们正在加扰输入0 3 1 4 2 中的字符 - 例如,如果输入为message,则输出将为abcde。这是一个非常弱的密码,它只是转换字符:

adbec
相关问题