Apr-11-2021, 01:15 PM
The term "flags" is used to mean a lot of different things, but I think you are talking about using a variable to signal that something happened. In this context flags are just variables. You can use a flag in an if-else statement, but a flag is not a substitute for else.
found = False # I have not found a line containing 123 with open('C:/02/somefile.txt','r') as file: for line in file: if '123' in line: found = True # I found a line break if found: # Did I find a line? print(line) # Do lots of additional processingA flag is used when there is space between finding and acting on the condition you are interested in. In the example below verbose is a flag used to signal that '--verbose' was contained in the command line arguments.
import sys verbose = '--verbose' in sys.argv: with open(sys.args[1], 'r') as file: for line in file: if verbose: print(line) if '123' in line: break