Conditional Statements Revisited¶

Outline¶

  • Or Conditional
  • And Conditional
  • Not Conditional

We will now expand our use of conditional statements by allowing for multiple conditions.

Reminders:

1) Use print statements check what your code is doing (or not doing) as you write it

2) Comment your code!


In [15]:
# load packages
import numpy as np
import matplotlib.pyplot as plt
import time

Or Conditionals ¶

We can check multiple statements using the or statement. Let's see this in a simple if statement (no functions).

In [18]:
x = -4

if x > 0 or x < 0:
    print('positive or negative')
positive or negative

Practice! Write a function that uses an or statement

And Conditionals ¶

Similarly, if you want to check more than one statement, you can do so in if statements by including and.

In [27]:
def myfun(x):
    # this checks if x is between 0 and 3
    if x > 0 and x < 3:
        #print(x)
        return x
    else:
        return x - 5
In [30]:
myfun(2.0) + myfun(1)
Out[30]:
3.0

Practice! Write a function (with comments) that returns the number only if the input is an integer and is divisible by 3.

Not Conditionals ¶

In [31]:
x = 3
if not x == 3:
    print(x)
In [14]:
x = 5
if x != 3:
    print(x)
5
In [ ]:
 

Practice! Write a function (with comments) that incorporates the not or != conditional.

Practice! Write two different functions that uses all 3 (or, and, not) - in different order. What do you think the order of operations is? In other words, what order does the computer perform or, and, not?

In [32]:
y = np.zeros(1000)
for i in range(1000):
    y[i] = myfun(i)
In [34]:
plt.plot(np.arange(0,1000), y)
Out[34]:
[<matplotlib.lines.Line2D at 0x115249b38>]
In [ ]:
# Is the order
# AON - 1
# ANO - 0
# NAO - 6
# NOA - 0
# Left to Right - 4
# OAN - 1
# ONA - 0