⊗pyPmLpLEC 163 of 208 menu

Intercepting Loop Exit in Python

To shorten the code when working with flags, you can use an alternative syntax - without declaring a special variable with boolean values.

Let's rewrite the example from the previous lesson. In the if block, when the first negative number is encountered, we set the output '---' and the instruction break. In the case when all the elements of the list are positive, the else block of the loop will output '+++':

lst = [1, 2, 3, -4, 5] for el in lst: if el < 0: print('---') break else: print('+++') # '---'

Now let's change the negative number to a positive one and check the list again:

lst = [1, 2, 3, 4, 5] for el in lst: if el < 0: print('---') break else: print('+++') # '+++'

Given a list, check if all its elements are even numbers.

Given a string:

tst = 'abcdef'

Check if it includes the character 'd'.

byenru