繁体   English   中英

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

[英]could someone please explain this simple python code?

我进入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循环是如何工作的,但我只是不明白这个是如何工作的。

谢谢!

这些行是非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 ,它接收消息长度中的每个第三个索引并访问message数组中的相应位置,将该字符附加到该位置并将结果累积到ciphered_msg变量中。 例如,如果message的长度为5 ,则将按以下顺序访问message的索引:

0 3 1 4 2

所以基本上我们在输入message加扰字符 - 例如,如果输入是abcde则输出将是adbec 这是一个非常弱的密码,它只是转换字符:

# input
0 1 2 3 4 # original indexes
a b c d e # `message` variable

# output
0 3 1 4 2 # scrambled indexes
a d b e c # `ciphered_msg` variable

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM