Python – nice feature #1

I’ve been playing around with the official Python tutorial. I have to admit I like what I see so far. Python appears to have some very nice language features. The first really interesting one is the way you can specify an else statement for a for loop, for example:

# Create a list
a = ['cat', 'dog', 'mouse']

# Create a search string
search_str = "fish"

# Loop over the list
for x in a:
  if x == search_str:
    print "found ", search_str
    # Break to leave the loop
  # Following executed if break is not called and loop finishes
  print "not found"

This is great – how many times do you just want to check if something exists in a list? In other languages I’ve used such as Java and ColdFusion, you need to do a whole flag/boolean setting exercise to find out if you came across the object in the loop.

This is much neater.

This entry was posted in regular and tagged , . Bookmark the permalink.

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s