Python - Caeser Cipher Not Giving Right Output

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Mar 20 23:58:43 EDT 2014


On Thu, 20 Mar 2014 20:23:49 -0700, dtran.ru wrote:

> Thanks for your input Dave. Would the line be:
> 
> return numtochar(c1 + c2 %26)

Yes, that's the line that Dave is talking about.

The critical part is that expression "c1 + c2 %26" which gets calculated 
before being passed on to numtochar. The % operator is a form of division 
(it returns the remainder after division, so 12%5 returns 2) and like the 
regular division operator / and multiplication * it has higher precedence 
than addition.

That means that "30 + 40 % 26" calculates the % part first:

30 + 40 % 26
=> 30 + 14
=> 54

What you probably want is to calculate the % last, not first. That means 
you need to perform the addition first. Use round brackets (parentheses) 
for that:

(30 + 40) % 26
=> 70 % 26
=> 18


Does that help?




-- 
Steven D'Aprano
http://import-that.dreamwidth.org/



More information about the Python-list mailing list