python退出循环快捷_Python:退出循环?

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!

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值