Вопрос №56516 от пользователя Алексей в уроке «Изменение множеств», курс «Python: Cловари и множества»
Функция toggle() Эта функция должна принимать флаг (один!) и множество в качестве аргументов. Если флаг уже присутствует в множестве, его нужно из множества убрать. Если же флаг отсутствует, то его нужно добавить.
Далее, исходя из приведенного примера:
READ_ONLY in flags
READ_ONLY in flags
Данное условие и пример указывают на то, что есть один флаг и множестов. В примере есть строка READ_ONLY и есть множество flags (почему-то во множественом числе). Присутвует ли флаг во множестве? Что есть множество, исходя из примера, это очевидно — flags, но почему-то названный «flags». Далее следует разобраться, что флагом явялется строка READ_ONLY.
flags — множество, то есть значение типа set() . Множество хранит те флаги — произвольное количество флагов(!), которые в данный момент «включены». Флаг считается включенным, если присутствует во flags , и выключенным, если отсутствует. Поэтому проверка на вхождение флага в множество flags как раз и возвращает состояние «включенности» флага. А функция toggle() переключает состояние флага на противоположное, изменяя состояние множества.
>>> # один конкретный флаг >>> READ_ONLY = 'read_only' >>> # множество включенных флагов >>> flags = set() # множество пустое, т.е. все флаги выключены >>> # переключаем состояние флага >>> toggle(READ_ONLY, flags) >>> # проверяем состояние флага >>> READ_ONLY in flags True >>> # True значит, что флаг включен >>> # переключаем опять и проверяем состояние >>> toggle(READ_ONLY, flags) >>> READ_ONLY in flags False >>> # флаг выключен
flags — множество, то есть значение типа set().
Множество хранит произвольное количество флагов, которые в данный момент «включены». «Включен» — присутствует во множестве. «Выключен» — не присутствует во множестве. Например, при flags = <>, количество включенных флагов — 0. При flags = , количество включенных флагов — 1. При flags = , количество включенных флагов — 2.
Флаг считается включенным, если присутствует во flags, и выключенным, если отсутствует. Например, во множестве flags = нужно считать флаги ‘read_only’, ‘write’ включенными, а флаг ‘copy’ выключенным.
Поэтому проверка на вхождение флага в множество flags как раз и возвращает состояние «включенности» флага.
Функция toggle() переключает состояние флага на противоположное, изменяя состояние множества при помощи добавления или исключения флага.
What is a flag in python while loops? [closed]
There’s no technical definition. A flag is just a variable whose value (usually Boolean) indicates a particular situation.
Nov 30, 2019 at 21:21
This needs more context, including example code. Otherwise it is unanswerable and will probably be closed.
Nov 30, 2019 at 21:23
Let’s say you’re looking for a needle in a haystack. You’d start with needle_found = False . That is a flag. while not needle_found is the criteria to keep going through the while loop. Once you find the needle, you set needle_found = True and the while loop stops
Nov 30, 2019 at 21:43
2 Answers 2
A flag in Python acts as a signal to the program to determine whether or not the program as a whole or a specific section of the program should run.
In other words, you can set the flag to True and the program will run continuously until any type of event makes it False. Then the program, loop, or whatever you’re using a flag for will stop.
prompt = "Tell me something cool: " prompt += "\nEnter 'quit' to end the program" active = True while active: message = input(prompt) if message == 'quit' active = False else: print(message)
In this example you can see that if a user types ‘quit’, it will end the program because it sets your flag to False thus stopping and exiting the while loop.
Переменные-флаги
В старые времена с помощью флагов командовали войсками. Например, если флаг поднят — нужно атаковать, опущен — отступать.
В программировании “флагом” называют переменную булевого типа, т.е. в которой хранится либо True , либо False . Их так называют потому, что управление с их помощью похоже на флаги: есть всего 2 варианта, флаг или поднят, или опущен.
Например, вам интересно, есть ли человек на видео. Вы пишете функцию, которая проходит по кадрам видео и проверяет каждый из них. Если найдёт человека, то сообщит об этом:
def check_human_in_video(video): human_found = False for frame in video: if frame.has_human(): human_found = True print(human_found)
Обратите внимание, что True и False написаны без кавычек! Так и задумано — это не строки, а отдельный тип данных.
По умолчанию считаем, что человека нет, поэтому создаём флаг human_found = False . Далее для каждого кадра в видео проверяем, есть ли на нём человек — вызываем метод объекта frame.has_human() . Если человек найден, то меняем флаг на True . В конце выводим флаг с помощью print .
Если ни на одном кадре человек не найдётся, то флаг так и останется False , потому что условие if frame.has_human() ни разу не сработает.
Если хоть на одном кадре есть человек, то при обработке этого кадра сработает условие if frame.has_human() и флаг станет True .
Как улучшить код
Теперь усовершенствуем код. Функция станет удобнее, если откажется от вывода на экран в пользу return .
def is_human_in_video(video): human_found = False for frame in video: if frame.has_human(): human_found = True return human_found print(is_human_in_video(video))
Следующим шагом ускорим работу функции. Сейчас код продолжит проверку, даже если встретит человека на самом первом кадре видео. Если кадров в video будет много, то проверка займёт время. Это даёт возможность для оптимизации. Прервём проверку сразу, как только станет ясен результат:
def is_human_in_video(video): human_found = False for frame in video: if frame.has_human(): human_found = True return human_found return human_found print(is_human_in_video(video))
Теперь заметно, что от переменной human_found можно избавиться, сделав код немного лаконичнее:
def is_human_in_video(video): for frame in video: if frame.has_human(): return True return False print(is_human_in_video(video))
Но и это ещё не всё. Флаги являются таким частым приёмом, что они попали в стандартную библиотеку Python. Код выше можно записать в одну строку:
def is_human_in_video(video): return any(frame.has_human() for frame in video)
- Про функцию any
- Что такое list comprehension?
Попробуйте бесплатные уроки по Python
Получите крутое код-ревью от практикующих программистов с разбором ошибок и рекомендациями, на что обратить внимание — бесплатно.
Переходите на страницу учебных модулей «Девмана» и выбирайте тему.
What Is a Flag in While Loops?

Using flag variables in while loops are standard in python and other languages. It’s a nomenclature used for a boolean variable that denotes when to get out of a loop. In this article, we’ll be getting deep into the use of this flag and why it is necessary to use it in while loops. Let’s get started!
Loops
Loops are used to continually run a specific block of code. While loop is a type of loop that loops through a block of code until a certain condition is met. While loop is a common yet powerful tool in programming.
Syntax for while loop
while (condition): #code to be looped goes here
While loop can be used by using the keyword ‘while’ and then writing the condition in the same line, the code block intended after this line will be looped until the condition is met. The indentation marks the code inside the loop in python.
A Simple Example to Demonstrate While Loop
i = 10 #declaring a variable i with value 10 while i!=0: # looping the code block until the value of i is not equal 0 print(i) i-=1

First, we set “i” in the example above to have a value of 10. After that, a while loop was initiated with the constraint that i!= 0. i.e., until the value of i is not equal to 0, the interpreter will execute the block of code. We print the value of i and then each time decrease its value by 1 in the code block contained within the loop. As a result, the interpreter repeats printing the value of i until the value of i equals 0, at which point it exits the loop.
Consequently, the value we specify for i, which is 10, is the first value printed. The interpreter then reads the next line, which is i-=1, after printing the value of i. The value of i is set to i-1 in this line. As a result, i now have a value of 10-1 which is 9. The interpreter now determines if i=0 or not. The interpreter resumes running the code block since the value of i is 9. It now displays the value of i (i=9) before setting it once more to i=i-1 (i = 9-1 = 8).
When the value of i finally equals 0, the interpreter pauses running the code block and checks once more to see whether the value of i=0. whether it is or not, it keeps printing the value of i and reducing it by 1 until it is.
Related: Learn more about while loops
Flag variable
A flag is a common nomenclature used for a variable that takes a boolean value and serves as a marker for a specific condition. Depending on how we utilize it, it can be used anywhere in the program and be quite helpful. Most frequently, a flag is employed as a while loop condition. The loop would continue while the flag’s value was True and end if it became False.
Let’s check an example of it to have a better understanding of how exactly we can use the flag variable,
flag = True # initializing flag with true value i=10 # initializing i with value 10 # Started a loop with a condition that flag==True while flag: print(i) if i==1: flag = False # changing the value of flag to False in a way that the loop terminates before printing 0 else: i-=1

In the last example, we carried out the identical action, but this time we used a flag variable. The flag’s value was set to True, and the while loop was executed with the flag serving as the condition. Till we don’t set the flag’s value to False, the loop will continue to execute.
We now began printing i’s value. If i == 1, we set an if condition in the code block to modify the flag’s value to False. Therefore, the next time the interpreter tries to iterate over the loop, the loop terminates as the value of the flag is False now. This is because as soon as the value of i changes to 1, the interpreter will alter the value of the flag to False.
We can use the flag variable in different ways, like marking a condition we will check later in the program.
Let’s write a program to check if a number is prime or not using a flag variable,
flag = True # initializing flag with true value for i in range(2): n=int(input("Enter a number:")) # Take a number as input from the user # Run a loop on all the numbers smaller than n and check if any of them divides n for i in range(n-1,1,-1): if n%i==0: flag = False #check the value of flag and print if the the number is prime or not if flag: print("The number is prime") else: print("The number isn't prime")

In the above program, we checked whether a given number is prime. First, we initialized a flag variable with the True value. Then we used a for loop to perform the following code block 2 times. Then we ran a loop, starting with the value of i as n-1 till the value of i becomes 1 and then breaking out of the loop. Now the next 2 lines of code, “if n%i==0” and “flag=False,” check if n gives remainder 0 when divided by i. If it does, i.e., n is divisible by any number from n-1 to 2, the flag’s value will be set to False, marking that the number is not a prime number.
Later, we have to check if the flag’s value is True or False, and we can determine if the number is prime or not.
Similarly, we can use flags in many ways; we just need to know when to use them. Just keep programming, and you’ll understand when we can use the flag and don’t need it.
Conclusion
I hope you understand the significance of the flag variable. It’s not that big, but an essential concept of programming. We must know how to use things to our advantage in different conditions as programmers. Flags can be proven very powerful if used properly.
References
stack overflow answer for the same question.