I am new to Python and having a problem with the modulo.
Here is the code:
for i in range(ord('a'), ord('z')+1):
print chr(((i+2) % 97) + 97 )
The exptected result is cdef...a. However I am not getting the desired module behavior of wrapping around once we get to z.
Because 97 isn’t what you want to be wrapping at – you want to be wrapping at
ord('z')= 122, and then adding the value oford('a')(97).The full math you really need to be doing is to shift into an offset, and then back to the set. For instance…
The reason your existing code isn’t working is because your
i+2will always be greater than 97 (since youristarts atord('a')which is 97, and goes up from there), so the% 97is effectively just- 97, and thus your print line is effectively this:which reduces to…
which is obviously just
print chr(i+2).