Python break from if statement to else
break
is used when you want to break out of loops not if statments. You can have another if
statement that executes this logic for you like this:
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
What this snippet is doing is evaluating two booleans, both are for the else
part. However, it says either execute in case of else
from first if
or in case of (i+1 == (len(s)-1))
Jim
Updated on June 12, 2022Comments
-
Jim almost 2 years
(I'm a Python newbie, so apologies for this basic question, I for some reason couldn't find an answer to.)
I have a nested
if
statement with theif
statement of anif
/else
block. In the nestedif
statement, if it it meets the criteria, I'd like the code to break to theelse
statement. When I put abreak
in the nestedif
, though, I'm not sure if it's breaking to theelse
statement.I'd like to find the longest substring in alphabetical order of a given string,
s
. Here's my code: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])
(Yes, I realize there's surely lots of unnecessary code here. Still learning!)
At this nested
if
:if (i+1 == (len(s)-1)): break
...if
True
, I'd like the code to break to theelse
statement. It doesn't seem to break to that section, though. Any help? -
Jim over 7 yearsI believe the first if statement should have an and boolean as well: if (s[i] <= s[i+1]) and (i+1 < (len(s)-1)): alpha_count += 1 elif (s[i] <= s[i+1]) and (i+1 == (len(s)-1)):
-
Kafo over 7 yearsif you want the first one to execute whenever
i + 1 < (len(s) - 1)