2. Notebook
2. Notebook
Data types
Numbers
In [1]: 6-3
3
Out[1]:
In [2]: 1 + 1
2
Out[2]:
In [3]: 1 * 3
3
Out[3]:
In [4]: 1 / 2
0.5
Out[4]:
In [5]: 2 ** 4
16
Out[5]:
In [6]: 4 % 2
0
Out[6]:
In [7]: 5 % 2
1
Out[7]:
In [8]: (2 + 3) * (5 + 5)
50
Out[8]:
Variable Assignment
In [9]: # Can not start with number or special characters
name_of_var = 2
In [10]: x = 2
y = 3
In [11]: z = x + y
In [12]: z
5
Out[12]:
Strings
In [13]: 'single quotes'
'single quotes'
Out[13]:
'double quotes'
Out[14]:
Printing
In [16]: x = 'hello'
In [17]: x
'hello'
Out[17]:
In [18]: print(x)
hello
In [19]: num = 12
name = 'Samiul'
Lists
In [22]: [1,2,3]
[1, 2, 3]
Out[22]:
In [23]: [1,2,2,33]
[1, 2, 2, 33]
Out[23]:
In [24]: ['hi',1,[1,2]]
In [26]: my_list.append('d')
In [27]: my_list
In [28]: my_list[0]
'a'
Out[28]:
In [29]: my_list[1]
'b'
Out[29]:
In [30]: my_list[1:]
In [31]: my_list[:1]
['a']
Out[31]:
In [32]: my_list[:2]
['a', 'b']
Out[32]:
In [34]: my_list
4
Out[36]:
In [37]: nest[3]
[4, 5, ['target']]
Out[37]:
In [38]: nest[3][2]
['target']
Out[38]:
In [39]: nest[3][2][0]
'target'
Out[39]:
In [41]: nest[3][2][1]
'bme'
Out[41]:
Dictionaries
In [42]: d = {'key1':'item1','key2':'item2'}
In [43]: d
In [44]: d['key1']
'item1'
Out[44]:
In [45]: d['key1']='BME'
In [46]: d
In [48]: d
{'key2': 'item2'}
Out[48]:
In [49]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)## Duplicates Not Allowed
In [50]: len(thisdict)
3
Out[50]:
Booleans
In [51]: True
True
Out[51]:
In [52]: False
False
Out[52]:
Tuples
In [53]: t = (1,2,3)
In [54]: t[0]
1
Out[54]:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[55], line 1
----> 1 t[0] = 'NEW'
Sets
In [58]: {1,2,3}
In [59]: {1,2,3,1,2,1,2,3,3,3,3,2,2,2,1,1,2}
{1, 2, 3}
Out[59]:
Comparison Operators
In [60]: 1 > 2
False
Out[60]:
In [61]: 1 < 2
True
Out[61]:
In [62]: 1 >= 1
True
Out[62]:
In [63]: 1 <= 4
True
Out[63]:
In [64]: 1 == 1
True
Out[64]:
False
Out[65]:
Logic Operators
In [66]: (1 > 2) and (2 < 3)
False
Out[66]:
True
Out[67]:
In [68]: (1 == 2) or (2 == 3) or (4 == 4)
True
Out[68]:
Yep!
In [70]: if 1 < 2:
print('yep!')
yep!
In [71]: if 1 < 2:
print('first')
else:
print('last')
first
In [72]: if 1 > 2:
print('first')
else:
print('last')
last
In [73]: if 1 != 2:
print('first')
elif 3 == 3:
print('middle')
else:
print('Last')
first
for Loops
In [74]: seq = [1,2,3,4,5]
1
2
3
4
5
Yep
Yep
Yep
Yep
Yep
2
4
6
8
10
while Loops
In [78]: i = 1
while i < 5:
print('i is: {}'.format(i))
i = i+1
i is: 1
i is: 2
i is: 3
i is: 4
range()
In [79]: range(5)
range(0, 5)
Out[79]:
0
1
2
3
4
In [81]: list(range(-3,3))
In [82]: list(range(-3,4))
list comprehension
In [83]: x = [1,2,3,4]
In [84]: out = []
for item in x:
[Link](item**2)
print(out)
[1, 4, 9, 16]
[1, 4, 9, 16]
Out[85]:
functions
In [86]: def my_func(param1='default'):
"""
Docstring goes here.
"""
print(param1)
In [87]: my_func
<function __main__.my_func(param1='default')>
Out[87]:
In [88]: my_func()
default
new param
new param
In [93]: print(out)
Example
Define a function arithmeticIf(v, a, b, c) that returns a if v is greater than 0, b if v is equal
to 0, and c if it is less than 0. Your function should have type (num, , , ) -> , where, by *
we mean that it could be any type.
Peter
In [ ]:
lambda expressions
In [95]: def times2(var):
return var*2
In [96]: times2(2)
In [98]: x(2)
4
Out[98]:
mytripler = myfunc(3)
print(mytripler(11))
33
In [101… map(times2,seq)
<map at 0x1a25b1eb7c0>
Out[101]:
In [102… list(map(times2,seq))
[2, 4, 6, 8, 10]
Out[102]:
[2, 4, 6, 8, 10]
Out[103]:
<filter at 0x1a25b231130>
Out[104]:
[2, 4]
Out[105]:
methods
In [106… st = 'Hello Clarice'
In [107… [Link]()
In [108… [Link]()
'HELLO CLARICE'
Out[108]:
In [109… [Link]()
['Hello', 'Clarice']
Out[109]:
In [111… [Link]('#')
In [112… [Link]('#')[1]
'Sports'
Out[112]:
In [113… d = {'key1':'item1','key2':'item2'}
In [114… [Link]()
dict_keys(['key1', 'key2'])
Out[114]:
In [115… [Link]()
In [117… [Link]()
3
Out[117]:
In [118… lst
[1, 2]
Out[118]:
False
Out[119]:
True
Out[120]:
Using NumPy
Once you've installed NumPy you can import it as a library:
In [122… print([Link](1,10))
In [123… print([Link](1,10,5))
In [124… print([Link](1,10,5))
Numpy has many built-in functions and capabilities. We won't cover them all but instead we
will focus on some of the most important aspects of Numpy: vectors,arrays,matrices, and
number generation. Let's start by discussing arrays.
Numpy Arrays
NumPy arrays are the main way we will use Numpy throughout the course. Numpy arrays
essentially come in two flavors: vectors and matrices. Vectors are strictly 1-d arrays and
matrices are 2-d (but you should note a matrix can still have only one row or one column).
[1, 2, 3]
Out[125]:
In [126… [Link](my_list)
array([1, 2, 3])
Out[126]:
In [128… [Link](my_matrix)
Built-in Methods
There are lots of built-in ways to generate Arrays
arange
Return evenly spaced values within a given interval.
In [129… [Link](0,10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Out[129]:
In [130… [Link](0,11,2)
array([ 0, 2, 4, 6, 8, 10])
Out[130]:
In [131… [Link](3)
In [132… [Link]((5,5))
In [133… [Link](3)
In [134… [Link]((3,3))
linspace
Return evenly spaced numbers over a specified interval.
In [135… [Link](0,10,3)
In [136… [Link](0,10,50)
eye
Creates an identity matrix
In [137… [Link](4)
Random
Numpy also has lots of ways to create random number arrays:
rand
Create an array of the given shape and populate it with random samples from a uniform
distribution over [0, 1) .
In [138… [Link](2)
array([0.50550964, 0.25166773])
Out[138]:
In [139… [Link](5,5)
randn
Return a sample (or samples) from the "standard normal" distribution. Unlike rand which is
uniform:
In [140… [Link](2)
array([0.05655596, 0.07164435])
Out[140]:
In [141… [Link](5,5)
randint
Return random integers from low (inclusive) to high (exclusive).
In [142… [Link](1,100)
9
Out[142]:
In [143… [Link](1,100,10)
In [145… arr
In [146… ranarr
Reshape
Returns an array containing the same data with a new shape.
In [147… arr=[Link](1,10,25)
print(arr)
In [148… print([Link])
(25,)
In [149… [Link](5,5)
In [150… print([Link])
In [151… arr_new=[Link](5,5)
In [152… print(arr_new.shape)
(5, 5)
In [153… a=[1,2,3]
In [154… b=[Link]()
In [155… b[0]=71
In [156… a
[1, 2, 3]
Out[156]:
In [157… b
[71, 2, 3]
Out[157]:
In [158… ranarr
In [159… [Link]()
49
Out[159]:
In [160… [Link]()
9
Out[160]:
In [161… [Link]()
4
Out[161]:
In [162… [Link]()
1
Out[162]:
Shape
Shape is an attribute that arrays have (not a method):
In [163… # Vector
[Link]
(25,)
Out[163]:
In [165… [Link](1,25).shape
(1, 25)
Out[165]:
In [166… [Link](25,1)
array([[ 1. ],
Out[166]:
[ 1.375],
[ 1.75 ],
[ 2.125],
[ 2.5 ],
[ 2.875],
[ 3.25 ],
[ 3.625],
[ 4. ],
[ 4.375],
[ 4.75 ],
[ 5.125],
[ 5.5 ],
[ 5.875],
[ 6.25 ],
[ 6.625],
[ 7. ],
[ 7.375],
[ 7.75 ],
[ 8.125],
[ 8.5 ],
[ 8.875],
[ 9.25 ],
[ 9.625],
[10. ]])
In [167… [Link](25,1).shape
(25, 1)
Out[167]:
dtype
You can also grab the data type of the object in the array:
In [168… [Link]
dtype('float64')
Out[168]:
In [172… x
In [173… y
In [174… [Link]
To begin we create a figure instance. Then we can add axes to that figure:
[Link](x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title');
[Link]("[Link]", dpi=200)
ax = fig.add_axes([0,0,1,1])
<[Link] at 0x1a25d878700>
Out[178]:
We can also define colors by their names or RGB hex codes and optionally provide an alpha
value using the color and alpha keyword arguments. Alpha indicates opacity.
[<[Link].Line2D at 0x1a25d8cb5b0>]
Out[179]:
To change the line width, we can use the linewidth or lw keyword argument. The line
style can be selected using the linestyle or ls keyword arguments:
# custom dash
line, = [Link](x, x+8, color="black", lw=1.50)
line.set_dashes([5, 10, 15, 10]) # format: line length, space length, ...
# possible marker symbols: marker = '+', 'o', '*', 's', ',', '.', '1', '2', '3', '4
[Link](x, x+ 9, color="blue", lw=3, ls='-', marker='+')
[Link](x, x+10, color="blue", lw=3, ls='--', marker='o')
[Link](x, x+11, color="blue", lw=3, ls='-', marker='s')
[Link](x, x+12, color="blue", lw=3, ls='--', marker='1')