if/else
There are many times in life where what we would like to do next depends on some aspect of what’s currently happening at this moment. For example, when you wake up in the morning you may decide to wear a sweatshirt if it’s cold outside or just a t-shirt if it’s not. Python provides a way to express the same structure via conditionals.
if temperature == 'cold':
print("I will wear a sweatshirt")
else:
print("I will wear a t-shirt")
In the above code block, Python first evaluates the condition that follows the if
keyword: temperature == 'cold'
. Temperature must have been previously defined or else Python will throw an error. So assuming that it has been defined, Python will evaluate this expression as either True
or False
. If True
, Python will run the indented code block beneath the condition. In our example, we’d see “I will wear a sweatshirt” printed to the screen. If False
, though, Python will skip the code block beneath the if condition. It won’t run it. Instead it will jump to the indented code block beneath else
and run that.
Head of Macro
As second example and a bit of a tangent, Matt Levine from Bloomberg has been covering a lawsuit over whether James Fishbeck was ever the “Head of Macro” at Greenlight Capital Inc. According to Matt’s telling, James’ title was Research Analyst. That is, within Greenlight Capital Inc., he was an analyst — one level below Associate. However, when James was introduced on a call or in a meeting to outside individuals, he was referred to as the Head of Macro. Again according to Matt, this arrangement made everyone happy. The clients preferred to engage with the Head of Macro. We write the code which introduces James as follows
def introduction(other_person):
if other_person == 'colleague':
print("This is James, a Research Analyst")
else:
print("This is James, Head of Macro")
Options
if (option == 'call') & (strike_price < stock_price):
profit = stock_price - strike_price - payment
elif (option == 'put') & (strike_price > stock_price):
profit = strike_price - stock_price - payment
else:
profit = - payment