Variables, types (e.g., int
vs float
, list
, and bool
), defining functions, if-else conditionals
import math10
import math
both double quotation and single are for strings.
"This is a string"
'This is a string'
'This is another string'
'This is another string'
# adding strings is string concatenation
"hel" + "lo"
'hello'
2*'hello'
'hellohello'
2*"hello"
'hellohello'
How to use variables in Python.
# this is how you assign a variables
x = 2
y = 3
x+y
5
x**2 + x + 1
7
x
2
# you can re-assign and lose the old value
x = 3
x+y
6
# variables can hold strings as well
strng1 = "will print"
strng1
'will print'
# strings can use single quotation or double quotation
strng2 = 'will print'
strng1 == strng2
True
print("okay")
okay
# by the way, print is a handy function, if you want to print more than one value
print("help")
print()
print(x,"\n")
print("print " + strng1, 1, 2, x, x+1)
help 3 print will print 1 2 3 4
# strings format using floats
print('Our float value is %s. Our int value is %s.' % (3.14,1))
Our float value is 3.14. Our int value is 1.
a = 1
type(a) # a is an integer
int
b = 1.0
type(b)
float
type(3.14)
float
# division by integer has float type
type(2/2)
float
# let's look at some other types
type("hellooo") # str means string
str
abs(-3.14)
3.14
# even functions have a type
type(abs)
builtin_function_or_method
math.log(10)
2.302585092994046
type(math.cos)
builtin_function_or_method
# even modules have type
type(math)
module
Types are important in programming. we must always think about the types of the objects you are working with.
So far, the types we have seen are: int, float, string, function (and builtin_function).
Lists represent sequences of objects (which are variables but are associated with methods).
Lists allow us to store lots of things in memory.
Here is how to define them:
emptylist = []
type(emptylist)
list
# defining lists:
xs = [1,2,4,8,16,'hello']
print(xs)
[1, 2, 4, 8, 16, 'hello']
# you can print individual elements
print('the first element of the list is:', xs[0])
print("the last element of the list is:", xs[-1])
the first element of the list is: 1 the last element of the list is: hello
# you can change elements
xs[0] = 999
print(xs)
[999, 2, 4, 8, 16, 'hello']
# get the length of a list
len(xs)
print('the length of this list is:', len(xs))
the length of this list is: 6
Keep in mind every variable is an object, which is associated with various methods
put the cursor after xs
. and press Tab
xs.
# adding a new element to a list:
xs.append("goodbye")
print(xs)
[999, 2, 4, 8, 16, 'hello', 'goodbye']
# concatenating lists using +
xs = [1,2,3,4]
print(xs + ["hello", "goodbye"])
print("but xs is still:", xs)
[1, 2, 3, 4, 'hello', 'goodbye'] but xs is still: [1, 2, 3, 4]
# to change xs
xs = xs + ["hello", "goodbye"]
print(xs)
[1, 2, 3, 4, 'hello', 'goodbye']
range(3)
range(0, 3)
# range is a built-in type (similar to list), and also a useful function to produce lists
for i in range(3):
print(i)
0 1 2
list(range(4)) # making a list of range(4)
[0, 1, 2, 3]
list(range(1,5))
[1, 2, 3, 4]
list(range(5, 20, 3)) # start, end, step; end is never reached
[5, 8, 11, 14, 17]
list(range(5,21,3))
[5, 8, 11, 14, 17, 20]
def f(x): # definition
# coding block here
return x*x # return value
f(2)
4
def k(x):
return 0
print(f(3),k(3))
9 0
def g(x=1): # default x =1 if no input is given
return x*x
g()
1
g(4)
16
# what is this going to do?
def g(x,y):
print("One day, I will pass the Turing test.")
z = x + y
return z # this is the output
z = 1/0 # we never get to this line
return z+1 # we never get to this line
g(1,2)
Let's import the library math10
(which is using matplotlib
to draw graphs)
def f(x):
return x**3
import math10
math10.graphfunction(f)
Now let us draw the most-used activation function in Neural Network, ReLU (rectified linear unit).
$$f(x) =
\begin{cases}
x & \text{if } x > 0
\\[1em]
0 & \text{ otherwise }
\end{cases}
$$
We need to use the if-else conditional.
def relu(x):
if x>0:
return x
else:
return 0.0
math10.graphfunction(relu)
else
is not needed every time there is an if
.
def safe_div(x,y):
if y == 0:
print("Dividing by zero is not allowed in this universe!")
return x/0.0000000000001
return x/y
safe_div(1,0)
In the example above, we have used expression like x>0
and y==0
, what do they do?
We can use the following to compare things
x < y
x <= y
x > y
x >= y
x == y
x != y
0<1
True
type(0<1) # bool means boolean
bool
0>1
False
type(1 != 0)
bool
type(True)
bool
type(False)
bool
and
, or
, not
Exercise: draw the following function $$f(x) = \begin{cases} 1 & \text{if } x\in [0,1/2] \\[1em] 0 & \text{ otherwise } \end{cases} $$
def f(x):
if (x>=0) and (x<=0.5):
return 1.0
else:
return 0.0
import math10
math10.graphfunction(f)
When the return value is numerical value of 1, use 1.0
instead in our program, because Python interpreter may confuse 1
with int
1 or boolean
1 (logical True).