Lecture 3

Last time: Variables, types, defining functions

Today:

  • a couple more things about variables and functions
  • If-else, comparisons, booleans

Exercise: What will this code do?

In [1]:
x = 1
y = 2
print(x,y)
y = x
x = y
print(x,y)
1 2
1 1

I actually wanted to swap x and y, how do I do it?

In [2]:
x = 1
y = 2
print(x,y)
z = x
x = y
y = z
print(x,y)
1 2
2 1


We also talked about the difference between local and global variables. For example.

In [3]:
def f(x):
    zzz = 1
    return x
In [4]:
zzz
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-33b02bc15ce9> in <module>()
----> 1 zzz

NameError: name 'zzz' is not defined

We get an error because zzz is a local variable (inside the function) not global variable.


Will there be an error?

In [5]:
ggg = 1
def f(x):
    return x+ggg

print(f(0))
1

No. No problem. Global variables can be used inside the function.

Now, what will the following code produce?

In [6]:
ggg = 1
def f(x):
    ggg = 2
    return x+ggg
f(0)
Out[6]:
2
In [7]:
# What about this?
print(ggg)
1

Aha! Something funny is happening here. In fact, when we said ggg=2 inside the function, that ggg was a new local variable, not the ggg from outside the function. This is a safety measure that prevents your functions from messing up the values of your global variables.

If you really want to change the value, you use the global keyword.

In [8]:
ggg = 1
def f(x):
    global ggg
    ggg = 2
    return x+ggg
print(f(0))
print(ggg)
2
2

The global keyword tells python that the ggg inside the function is actually a global variable, and not a new local variable that would disappear after the function is completed.



If-else

Let's import the library from the homework.

In [10]:
# importing graphfunction() and drawfunction()
import libmath9 as math9
In [11]:
def f(x):
    return x**2
In [12]:
math9.graphfunction(f)

Now we want to make a partial function, e.g. $$f(x) = \left\{ \begin{array}{ll} 0 & \mbox{if } x < 0 \\ x & \mbox{otherwise } \end{array} \right.$$

(by the way this function is called the RELU function)

We need to use the if-else syntax

In [13]:
def relu(x):
    if x > 0:
        return x
    else:
        return 0.0   # note: it gets confused if we put 0 instead of 0.0

math9.graphfunction(relu)

Actually, we could have written it like this:

In [14]:
def relu(x):
    if x > 0:
        return x
    return 0.0    # no need for else, because return will end the function anyway

math9.graphfunction(relu)



Like in the above example, you don't need to have an else every time there is an if.

In [15]:
def safe_div(x,y):
    if y == 0:
        print("Noooo. You are dividing by zero bruuuuh!")
        return x/0.0000000000001
    return x/y

safe_div(1,0)
Noooo. You are dividing by zero bruuuuh!
Out[15]:
10000000000000.0


Comparisons in python:

  • x < y
  • x <= y
  • x > y
  • x >= y
  • x == y
  • x != y


What is x < y anyway?

In [16]:
0 < 1
Out[16]:
True
In [17]:
1 < 0
Out[17]:
False
In [18]:
type(1 != 1)
Out[18]:
bool
In [19]:
type(False)
Out[19]:
bool

So there is a type called bool. It can have values True or False.




Exercise Let's make this one: $$f(x) = \left\{ \begin{array}{ll} 0.5 & \mbox{if } 0 \leq x \leq 0.5 \\ 0 & \mbox{otherwise } \end{array} \right.$$

In [20]:
def f(x):
    if x >= 0:
        if x <= 0.5:
            return 0.5
    return 0.0
In [21]:
math9.graphfunction(f)

Why not combine x >= 0 and x <= 0.5. We need to and them:

In [22]:
def f(x):
    if x >= 0 and x <= 0.5:
            return 0.5
    return 0.0
In [23]:
math9.graphfunction(f)


Boolean operations:

and, or, not

In [24]:
True and True
Out[24]:
True
In [25]:
False and True
Out[25]:
False
In [26]:
not True
Out[26]:
False
In [27]:
True or False
Out[27]:
True


Weird example: Life planner app

In [28]:
checking = 400
savings = 400
debt  = 700
rich_relative = False

if checking + savings - debt < 200 and not rich_relative:
    print("No more cold pressed juice for you!")
elif checking + savings - debt > 500 or rich_relative:
    print("Ordering cold pressed juice and reserving VIP table at club...")
else: 
    print("Do what's in your heart.")
No more cold pressed juice for you!



Good exercises:

  • Write a function valid_day(year, month, day) which tells you if a day exists or not.
  • Write a function is_last_digit_prime(n) which will return True if the last digit of n is prime