I came across "flag" in Python while loops; can anyone explain what that is?
2 Answers
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!
Comments
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`
needle_found = False. That is a flag.while not needle_foundis the criteria to keep going through thewhileloop. Once you find the needle, you setneedle_found = Trueand thewhileloop stops