Python - Caeser Cipher Not Giving Right Output

dtran.ru at gmail.com dtran.ru at gmail.com
Fri Mar 21 05:23:24 CET 2014


On Thursday, March 20, 2014 11:58:43 PM UTC-4, Steven D'Aprano wrote:
> 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/

Ooh I understand now! I've been coding for hours and exhaustion has gotten to my head. Many thanks all of you as I now know the source of my folly. 



More information about the Python-list mailing list