Conditionals#

Basic conditionals#

Conditionals are statements that evaluate to either True or False.
Here are some examples of conditional statements using numeric values:

print(17 < 17)
False
print(17 <= 17)
True
print(4.2 == 7.1)
False
print(4.2 != 7.1)
True

And here are a couple of other examples of conditional statements using strings instead:

print('this string' == 'this string')
True
print('this string' == 'something else')
False

Important

We use two equal signs == to test logical equality. We use != to mean “not equal to”.

As we have seen in earlier discussions, we use a single equal sign = to assign/define variables.

For lists, we can also use the special in and not in operators.

custom_list = [4, 5, 6, 7, 8]

print(7 in custom_list)
print(10 in custom_list)
print(10 not in custom_list)
True
False
True

if and else statements#

if#

if statements check whether a conditional is True or False.
If True, a block of indented code is executed.
If False, the indented code block is ignored.
Do not forget the colon at the end of the if statement.

stock_price = 45
computed_value = 60

if computed_value > stock_price:
    print('Buy the stock.')
Buy the stock.

Important

The lines following the if statement are indented. When a line is not indented, it will run regardless of the conditional.

Python cares about “white space”, and a tab is a white space character.

if 2 > 10:
    print('Buy the stock.')

print('Since this part is not indented, it will run no matter what.')
Since this part is not indented, it will run no matter what.

else#

We can use the else command if we want certain lines to run when the conditional statement is false.

computed_value = 20
stock_price = 45

if computed_value > stock_price:
    print('Buy the stock.')
else:
    print('Do not buy the stock.')

print('Since this line is not indented, it will run no matter what.')
Do not buy the stock.
Since this line is not indented, it will run no matter what.

We can also use if statements with string variables.

report_to_skip = '2017q4'
current_report = '2018q1'

if current_report != report_to_skip:
    print('Continue with current report:', current_report)
Continue with current report: 2018q1

Now let’s use an if statement to check whether something is in a list using the in operator.
Remember our competitors list? Check to see if another company is in that list.

all_competitors = ['AAPL','MSFT','TSLA','AMZN']

another_company = 'MMM'

if another_company in all_competitors:
    print(another_company, 'is a competitor')
else:
    print(another_company, 'is NOT a competitor')
MMM is NOT a competitor

We can also use boolean variables in our analysis.
Suppose we have manually defined a variable that tells us if today is Sunday.

today_is_sun = False

if today_is_sun:
    print("Tomorrow is Monday.")
else:
    print("Today is not Sunday.")
Today is not Sunday.

On a single line#

For simple expressions, we can put the entire if/else expression on a single line. For example, this:

stock_price = 45
computed_value = 60

if computed_value > stock_price:
    buy_it = True
else:
    buy_it = False

can instead be written like this:

stock_price = 45
computed_value = 60

buy_it = True if computed_value > stock_price else False
print(buy_it)
True

elif statements#

Lastly, we can use elif when there are mutually exclusive ranges/categories/bins that correspond to a set of outcomes. For example, we can use elif to categorize a company’s earnings per share (EPS) as “incredibly high”, “moderately high”, “positive”, or “negative”.

eps = 4.2

if eps >= 5.1:
    print('Earnings are incredibly high.')
elif eps >= 2.9:
    print('Earnings are moderately high.')
elif eps > 0:
    print('Earnings are positive.')
else:
    print('Earnings are negative.')
Earnings are moderately high.

Important

Use elif when you have mutually exclusive outcomes.

The following implementation does not have mutually exclusive print statements because it uses several independent if commands instead of incorporating the elif process.

eps = 4.2

if eps >= 5.1:
    print('Earnings are incredibly high.')
if eps >= 2.9:
    print('Earnings are moderately high.')
if eps > 0:
    print('Earnings are positive.')
else:
    print('Earnings are negative.')
Earnings are moderately high.
Earnings are positive.

Multiple conditionals#

Suppose we have defined the following variables:

nflx_price = 225
nflx_beta = 0.9
nflx_industry = 'entertainment'
nflx_eps = 7

And we would like to calculate and print the P/E ratio if the beta is larger than 1 and the company is in the “entertainment” industry. If either statement is false, then we will print out a statement saying the company does not match the criteria.

We can combine conditionals using the logical and operator.

if nflx_beta > 1 and nflx_industry == 'entertainment':
    nflx_pe = nflx_price / nflx_eps
    print(f'{nflx_pe:0.2f}')
else:
    print('Company does not meet criteria.')
Company does not meet criteria.

The or operator is also an option we can use if that is our preferred logic:

if nflx_beta > 1 or nflx_industry == 'entertainment':
    nflx_pe = nflx_price / nflx_eps
    print(f'{nflx_pe:0.2f}')
else:
    print('Company does not meet criteria.')
32.14