-2

I came across "flag" in Python while loops; can anyone explain what that is?

3
  • 5
    There's no technical definition. A flag is just a variable whose value (usually Boolean) indicates a particular situation. Commented Nov 30, 2019 at 21:21
  • 2
    This needs more context, including example code. Otherwise it is unanswerable and will probably be closed. Commented Nov 30, 2019 at 21:23
  • 3
    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 Commented Nov 30, 2019 at 21:43

2 Answers 2

7

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.

For example:

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.

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

-4

If you point to the below snippet from Tutorials Point then the 'flag' is a variable. Variables can have any values assigned to them. In this case it has a value of 1.

While executes the code after (until end of the line) the colon as long as the condition in parentheses is True. In this case the code will be executed forever.

#!/usr/bin/python

flag = 1
while (flag): print 'Given flag is really true!'
print "Good bye!"`enter code here`

2 Comments

Dear @roganjosh , please read carefully ! this is NOT my example - this is an example from tutorialspoint that I suspect is the source of the question
@dexter103 he is right, though. You shouldn't post a subpar answer and defend it by saying, that it came from somewhere else

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.