Search code examples
pythonloopsfor-loopexit

Python : Exiting for loop?


I did some research on SO and am aware that many similar questions have been asked but I couldn't quite get my answer. Anyway, I'm trying to build a library to "encrypt" a string with "Cesar's number" technique which means I have to take the string and replace each letters with another letter X positions away in the alphabet (I hope that makes sense). Here's my code:

from string import ascii_lowercase, ascii_uppercase

def creer_encodeur_cesar(distance):
    
    retour = lambda x: encodeur_cesar(x, distance)
    return retour

def encodeur_cesar(string, distance):
    tabLowerCase = list(ascii_lowercase)
    tabUpperCase = list(ascii_uppercase)
    tabString = list(string)
    
    l_encodedStr = []
    
    for char in tabString:
        position = 0
        if char == " ":
            pass
        elif char.isupper():
            #do something
               
        elif char.islower():
            for ctl in range(0, len(tabLowerCase)):
                position = ctl
                if char == tabLowerCase[ctl]:
                    if (ctl + distance) > 26:
                        position = ctl + distance - 25
                    char = tabLowerCase[position + distance]
                    l_encodedStr.append(char)
                    #How to break out of here??
                    
        
        encodedStr = str(l_encodedStr)

        return encodedStr

encodeur5 = creer_encodeur_cesar(5)
print(encodeur5("lionel"))

So, in my second elif statement, I want to break once I have successfully found and encrypted a character instead of looping through the whole alphabet. I have tried to use break but it broke out of the main for loop. Not what I want. I saw that I could use try except and raise but I don't quite know how I could do that and is it a good idea?

What's the best way to do this? What are the good practices in this case?

Any help would be appreciated and thanks in advance!


Solution

  • You can use the continue keyword.

    From the docs:

    >>> for num in range(2, 10):
    ...     if num % 2 == 0:
    ...         print "Found an even number", num
    ...         continue
    ...     print "Found a number", num
    Found an even number 2
    Found a number 3
    Found an even number 4
    Found a number 5
    Found an even number 6
    Found a number 7
    Found an even number 8
    Found a number 9