-2

This is a code for a simple encryption method.

if character in alphabet:
    position=alphabet.find(character)
    newPosition=(position-key)%26  # here 
    newCharacter=alphabet[newPosition]
    print("The encrypted character is: " + newCharacter)
    newMessage += newCharacter
    print(newMessage)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Areef Syed
  • 35
  • 1
  • 5
  • https://en.wikipedia.org/wiki/Modulo_operation – khelwood Jul 05 '17 at 20:51
  • There is reading PHP language documentation, probably a good thing to do if one is writing PHP code. If the quesstion is why is it used in this case: think. Hint: how many letters are there in the English language, how many letters in ASCII? – zaph Jul 05 '17 at 21:23

1 Answers1

3

The % sign in your code is a modulo operator - the remainder after integer division. E. g.

    13 % 5

gives the result 3

(as 13 divided by 5 is 2, and the remainder is 3.

MarianD
  • 13,096
  • 12
  • 42
  • 54
  • 1
    Note however that the modulo operator is overloaded differently for different objects. In the case of integers, it returns the remainder. The behavior could be completely different for other objects though. Such as string formatting for strings. – Christian Dean Jul 05 '17 at 21:00
  • 1
    @Christian - You are totally right but if OP has problem with the *base meaning* (and in his code it is obviously the integer operation), giving him the complicated answer would be less efective (IMHO). – MarianD Jul 05 '17 at 21:06
  • @ChristianDean I understand the role that modulo plays but I want to know why exactly there is a need to use it here. – Areef Syed Jul 05 '17 at 21:10
  • @AreefSyed That is not the question you asked. – zaph Jul 05 '17 at 21:28
  • Your comment was probably addressed to me - English alphabet has `26` letters and your encryption method uses the simple mono-alphabetic substitution cipher, so called *shift cipher* - substituting every letter in the plain text with a letter obtained by the constant shift (=key) in the alphabet. (Continues...) – MarianD Jul 05 '17 at 21:37
  • Supposing A=0, B=1, ... Z=25. If the shifted position is greater than 25, you wanted to continue again from the *start* of the alphabet. For example if key is 2, you want to substitute the `Z` character (=25) with the `B` character (=1). But `25 + 2 = 27` - out of the bounds. So you take `27 % 26` (as the remainder after division by 26 is always from 0 to 25) and you obtain the right number (1) for `B`. – MarianD Jul 05 '17 at 21:37