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 '+++':

pythonlst = [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:

pythonlst = [1, 2, 3, 4, 5]

for el in lst:
  if el < 0:
    print('---')
    break
else:
  print('+++') # '+++'
Задание 1

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

Задание 2

Given a string:

pythontst = 'abcdef'

Check if it includes the character 'd'.