⊗pyPmLpFl 162 of 208 menu

Working with Flags in Python

Flag is a special variable that can only take two values: True or False. Flags can be used to solve problems that check for the absence of something: for example, you can check that a list does not contain an element with a certain value.

Let's solve the following problem: given a list of numbers, we need to check whether all the elements in it are positive. To do this, we will define a special variable flag, which will be true before the start of the loop. And when a negative number gets into the loop, we will change its value to False. To find out the result of the check, we will output the variable flag to the console after the loop:

lst = [1, 2, 3, 4, 5] flag = True for el in lst: if el < 0: flag = False print(flag) # True since all numbers are positive

It's good practice to name a flag variable to reflect the condition you're trying to achieve. Let's rename flag to isAllPositive. And to make it clearer, let's change one number in the list to be negative:

lst = [1, 2, 3, -4, 5] isAllPositive = True for el in lst: if el < 0: isAllPositive = False print(isAllPositive) # False since there is a negative number

If there are many values ​​in the list being iterated and you want to stop the loop after the first negative number is found, you should use the break instruction:

for el in lst: if el < 0: isAllPositive = False break

When working with flags, to find out the result of executing a loop, you can output not the flag value, but an arbitrary message using the additional if.

Let's rewrite the previous example. If all elements are positive, then let the output be '+++', if not - '---':

for el in lst: if el < 0: isAllPositive = False break if isAllPositive: print('+++') else: print('---') # '---'

Given a list, check that all its elements are positive numbers.

Given an integer, check if it is prime, i.e. divisible only by one and itself.

byenru