Python : Exiting for loop?

可紊 提交于 2019-12-02 04:07:43

问题


I did some research on SO and am aware that many similar questions have been asked but I couldn't quite get my anwser. Anyway, I'm trying to build a library to "encrypt" a string with "Cesar's number" technique wich 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 succesfully found and encrypted a character instead of looping trough 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 exceptand 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!


回答1:


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


来源:https://stackoverflow.com/questions/35539925/python-exiting-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!