Reputation: 3
I was trying to create a program which would encrypt a message according to a key or number that the user would give. So for example the letter C with a key of 2 would change to the letter E. I was thinking of using either a saved dictionary or ordinal values for this though I'm unsure on how to limit it to 26 letters. For example, my code right now would look like this:
word = input("Please enter a word")
numkey = input("Please enter a key")
for ind in word:
encrypt = ord(ind) + int(numkey)
actual_encrypt = chr(encrypt)
The problem with this code is that I want to limit the encrypt value to 26 and to have it start over again once it reaches there. So instead of 27, for example, it would be 1 again. I'm just a little bit confused on how to set that up. Thank you.
Upvotes: 0
Views: 176
Reputation: 1838
If I understand right your word contains only the characters: a-z if so you can replace the line:
encrypt = ord(ind) + int(numkey)
with:
encrypt = ord('a') + (ord(ind) - ord('a') + int(numkey)) % 26
Upvotes: 2
Reputation: 503
If I understand your question correctly, the common way to solve this problem is using the modulo operator "%". This operator returns the remainder of an integer division between the operands.
It could look like this:
encrypt = ((ord(ind) + int(numkey)) % 27) + 1
If the result of ord(ind) + int(numkey)
is 27, % 27
results in 0 (hence the additional offset of 1).
Upvotes: 0
Reputation: 249602
You want the modulus operation, %
. For example, 27 % 26
gives 1
.
Upvotes: 0