Pythons ‘if’ conditions

The ‘if’ condition, being frequently used as it is, is not always well understood. Most of the people don’t care about the order of referenced conditions, which is fine. However, wanting to get most of it, one should consider putting the less compute demanding conditions first. Here is an example in Python:

>>> def one():
...   print '1'
...   return True
... 
>>> def two():
...   print '2'
...   return False
... 
>>> one() and two()
1
2
False
>>> two() and one()
2
False

As you can see, having two conditions linked with ‘and’, they are checked one at the time starting from left most. It is not magic. This is exactly what one would expect. If ‘if’ statement is able to make a decision during the evaluation, it will!

Advertisements

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