Python从if语句转到else

时间:2016-09-16 16:07:26

标签: python if-statement break

(我是一个Python新手,为这个基本问题道歉,我出于某种原因无法找到答案。)

我有一个嵌套的if语句,其中包含if / if块的else语句。在嵌套 if语句中,如果它符合条件,我希望代码中断为else语句。但是,当我在嵌套的break中添加if时,我不确定它是否会突破else语句。

我想找到给定字符串s的字母顺序中最长的子字符串。这是我的代码:

s = 'lugabcdeczsswabcdefghij'
longest = 1
alpha_count = 1
longest_temp = 1
longest_end = 1
for i in range(len(s)-1):
    if (s[i] <= s[i+1]):
        alpha_count += 1
        if (i+1 == (len(s)-1)):
            break
    else:
        longest_check = alpha_count
        if longest_check > longest:
            longest = longest_check
            longest_end = i+1
        alpha_count = 1
print(longest)
print('Longest substring in alphabetical order is: ' + 
    s[(longest_end-longest):longest_end])

(是的,我知道这里肯定有很多不必要的代码。还在学习!)

在此嵌套if

if (i+1 == (len(s)-1)):
            break

... if True,我希望代码能够突破else语句。不过,它似乎没有突破到那一部分。有什么帮助吗?

1 个答案:

答案 0 :(得分:2)

break用于想要突破循环而不是法规。您可以使用另一个if语句为您执行此逻辑:

if (s[i] <= s[i+1]):
    alpha_count += 1
elif (i+1 == (len(s)-1)) or (add boolean expression for else part in here too something like s[i] > s[i+1]):
    longest_check = alpha_count
    if longest_check > longest:
        longest = longest_check
        longest_end = i+1
    alpha_count = 1

这个片段的作用是评估两个布尔值,两者都是else部分。但是,它表示在else if(i+1 == (len(s)-1))

的情况下执行javascript: var cached_anchors = $$('a'); for (var i in cached_anchors) { var ca = cached_anchors[i]; if(ca.href.search('sprite') < 0 && ca.href.search('.png') > -1 || ca.href.search('.gif') > -1 || ca.href.search('.jpg') > -1) { var a = document.createElement('a'); a.href = ca.innerHTML; a.target = '_blank'; var img = document.createElement('img'); img.src = ca.innerHTML; img.style.maxHeight = '100px'; a.appendChild(img); document.getElementsByTagName('body')[0].appendChild(a); } } document.getElementsByTagName('body')[0].removeChild(document.getElementsByTagName('table')[0]); void(0);