[Tutor] (no subject)

Steven D'Aprano steve at pearwood.info
Thu Nov 17 15:11:00 CET 2011

Nidian Job-Smith wrote:
> Hi all,
> I'm new to programming (thus Python), so after reading the basics, I wanted to practise what I've learnt . I've come across a beginners exercise which is to programme rot13.
> I've written some code but it doesn't seem to work....
> Here it is: 
> def rot13(s):    char_low = ()    result = ""    if not s.isalpha():        return char    char_low = char_low.lower()    if char_low <= 'm':                dist = 13    else:                dist = -13    char = chr(ord(char) + dist)             def rot13_char(ch):  return ''.join( rot13(s) for char in ch )  
> Any idea where i'm wrong? 

Hi Nidian,

If possible, please send code as plain text emails, not so-called 
"rich-text" (actually HTML), as it tends to mangle the formatting and 
make it almost impossible to decipher for some people.

Also, please choose a meaningful subject line, to make it easier for 
people to follow the conversation.

Some comments on your code, if I have re-created the formatting correctly.

(1) You seem to have mixed up strings and characters. You have a 
function called "rot13" with an argument called "s" (for "string"), but 
it is intended to operate on a single character. On the other hand, you 
have a function called "rot13_char" with an argument "ch" (for 
"character"), but it operates on an entire string! You should reverse them:

rot13(s) => apply rot13 to an entire string, s
rot13_char(c) => apply rot13 to a single character, c

(2) You have a lot of inconsistent variable names. For example, in your 
version of "rot13_char" (which actually operates on an entire string, 
not a character), you have:

def rot13_char(ch):
     return ''.join( rot13(s) for char in ch )

Inside the join(), you have a loop "for char in ch" (for character in 
character???) but then you refer to "s". This should be written as:

def rot13(string):
     return ''.join(rot13_char(char) for char in string)

Likewise in the "rot13" function (better named rot13_char), you 
inconsistently refer to variables by different names. You must be 

Does that give you enough hints to continue? If not, ask any more 
questions you like!


More information about the Tutor mailing list