Reputation: 47
I am a few weeks into GCSE Computing, and I am in year 9. Today we went through a program that was a simple encryption program. I didn't really understand it that much. Could an experienced python programmer please explain this piece of code, simply?
BTW - I have put a comment by the pieces of code I understand.
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
Please help me with this, as I would really like some more python knowledge and to get an A* in my exam.
I know how a for loop works, but I just don't understand how this one works.
Thanks!
Upvotes: 1
Views: 238
Reputation: 235984
These lines are un-Pythonic and you should not do this:
ciphered_msg = str()
i = int()
j = int()
n = int(3)
Instead do this, it's completely equivalent code but simpler and clearer:
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
The loop is doing the following: starting in 0
, then 1
and finally 2
, it takes every third index in the message's length and accesses the corresponding position in the message
array, appending the character at that position and accumulating the result in the ciphered_msg
variable. For instance, if message
is of length 5
, the indexes in message
will be accessed in this order:
0 3 1 4 2
So basically we're scrambling the characters in the input message
- for example, if the input is abcde
the output will be adbec
. This is a very weak cipher, it's only transposing the characters:
# 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
Upvotes: 3