Home > Net >  How to check if a variable/loop in Python was True?
How to check if a variable/loop in Python was True?

Time:07-09

I'm learning Python and had a small issue. I have this loop:

found = None 
print ('Before', found)
for value in [ 41, 5, 77, 3, 21, 55, 6]:
    if value == 21:
        found = True
    else: 
        found = False 
    print (found, value)
print ('After', found)

The code is well, but the issue is print ('After', found) I want it to tell me that there was a True value found in the loop. Is there a way to keep the code the way it is and resolve the issue?

CodePudding user response:

You don't want to reset found to False once you've set it to True. Initialize it to False, then only set it to True if value == 21; don't do anything if value != 21.

found = False 
print ('Before', found)
for value in [ 41, 5, 77, 3, 21, 55, 6]:
    if value == 21:
        found = True
    print (found, value)
print ('After', found)

Ignoring the print statement in the loop, you could just use any:

found = any(value == 21 for value in [ 41, 5, 77, 3, 21, 55, 6])

or even

found = 21 in [ 41, 5, 77, 3, 21, 55, 6]
  • Related