Python Forum

Full Version: For loop not working
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm brand new to python and trying to figure out why my code isn't working. I'm trying to simulate the rot13 function, but my output only returns the first character despite being in a for loop?

def rot13(text, rotation):
        text = text.lower()
        
        alphabet = 'abcdefghijklmnopqrstuvwxyz'
        
        for letter in text:
            if letter == ' ':
                encrypted = ' '
            else:
                rotated = alphabet.index(letter) + int(rotation)
                if rotated > 26:
                    rotated = rotated % 26
                encrypted = alphabet[rotated]
                return encrypted

        
print(rot13('Hello there',13))
Probably you want the return out of the loop...
the loop is working, but you have a return that's executer on first pass.
use a debugger and step through your code.
it's because you put the return statement directly in your for loop. instead of storing the value and continue loop. not sure what you exactly trying to do, but i'm guessing you wanted to return the encrypted message.

def rot13(text, rotation):

        ret = ''
        text = text.lower()
        alphabet = 'abcdefghijklmnopqrstuvwxyz'
         
        for letter in text:
            if letter == ' ':
                ret = ret + ' '
            else:
                rotated = alphabet.index(letter) + int(rotation)
                if rotated > 26:
                    rotated = rotated % 26
                encrypted = alphabet[rotated]
                ret = ret + encrypted
            
        return ret
 
         
print(rot13('Hello there',13))
output: uryyb gurer
Oh I see, thank you!!