0

I have searched for this question and found some ways to do this. Some solutions were in one line too. There was one solution in which the data is stored in list and then the method append is used to make a word. The other methods are working .
Though I want to know what is wrong with my code.
EDIT 1 : The problem with my code is that is shows only the first alphabet of the input string in the output instead of the whole word.
here is my code :

alph = {"a":"n" , "b":"o" ,"c":"p" , "d":"q","e":"r" , "f":"s" , "g":"t" ,"h":"u" , "i":"v",  "j":"w", "k":"x" , "l":"y" , "m":"z" ,"n":"a", "o": "b" ,  "p":"c" ,"q":"d" ,"r":"e" ,"s":"f", "t":"g" ,"u":"h", "v":"i", "w":"j", "x":"k", "y":"l", "z":"m" }
def rot(word):
    rt = ''
    for c in word:
        if c.islower():
            rt += alph.get(c)
            return rt
        if c.isupper():
            c = c.lower()
            rt += alph.get(c).capitalize()
            return rt
        if c not in alph:
            rt += c
            return rt

word = raw_input("Enter:")
print rot(word)

Please check and tell me what is wrong in it.

4
  • What makes you think something is wrong with it? You tried it with some input and got the wrong output or an error? Commented Jun 29, 2017 at 2:47
  • Side-note: ROT13 in Python can be implemented with a one-time call to string.maketrans (Py2)/str.maketrans (Py3) and then using the result to call str.translate. No need for explicit loops at all. Commented Jun 29, 2017 at 2:48
  • Ryan , the output comes as a single first alphabet of the input string instead of the whole word. Commented Jun 29, 2017 at 2:54
  • Ok shadowranger, I will check the one you mentioned right now. Commented Jun 29, 2017 at 2:55

1 Answer 1

1

As the comments have mentioned, a more elegant way to do this is to use python's built-in string translate methods to avoid writing the loop by hand but if you have to write your own loop:

The reason your output comes back as only the first letter is that you return from each of your if statements in the for loop. This means that on the first iteration of the loop, the first character is translated, added to the rt string, and immediately returned from the function; the rest of the string is never translated.

To fix this, simply remove the return rt from the bottom of each if statement, and put a single return rt after the loop and at the end of the function.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the explanation . I changed it and now its working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.