Flags

Today I learned about the else clause in for loop in Python.
Usually I write such things with flags like


flag = false
for item in list:
if item == value:
# Found it!
print(item)
flag == True
break
if not flag:
print("Didn't find!")

But else is MUCH better!

for item in list:
if item == value:
#Found it!
print(item)
break
else:
print("Didn't find!")

Of course that’s a stub for bigger things. The simple functionality can be achieved with:

if item in list:
print(item)
else:
print("Didn't find!")
Advertisements

One thought on “Flags

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s