COP3990C - Python Programming


In [41]:
from IPython.core.display import HTML
def css_styling():
    styles = open("styles/custom.css", "r").read()
    return HTML(styles)
css_styling()


Out[41]:

Numbers

Arithmetic


In [42]:
123+321


Out[42]:
444

In [43]:
4*5.5


Out[43]:
22.0
Exponentiation: use **

In [44]:
2**5


Out[44]:
32

In [45]:
3**4


Out[45]:
81

In [46]:
81**0.5


Out[46]:
9.0

In [47]:
3+8*8


Out[47]:
67
How long is the number?

In [48]:
str(4**4)


Out[48]:
'256'

In [49]:
len(str(4**4))


Out[49]:
3

Division: be careful dividing integers - the result is an integer


In [50]:
# This rounds down (floor function)
float(20)/8


Out[50]:
2.5

In [51]:
20 // 8


Out[51]:
2

In [52]:
from __future__ import division
print 20 / 8
print 20 // 8


2.5
2

Warning: integer division gives back intergers. This may not be what you want.


In [53]:
20/8.0


Out[53]:
2.5

In [54]:
20/8.0


Out[54]:
2.5

In [55]:
20//8.0


Out[55]:
2.0

In [56]:
20 % 8.0


Out[56]:
4.0

In [57]:
divmod(20,8.0)


Out[57]:
(2.0, 4.0)

In [58]:
from math import *
print pi


3.14159265359

In [59]:
who


HTML	a	acos	acosh	asin	asinh	atan	atan2	atanh	
ceil	copysign	cos	cosh	css_styling	degrees	division	e	erf	
erfc	exp	expm1	fabs	factorial	floor	fmod	frexp	fsum	
gamma	hypot	isinf	isnan	ldexp	lgamma	log	log10	log1p	
math	modf	pi	pow	radians	random	sin	sinh	sqrt	
tan	tanh	trunc	x	y	

In [60]:
import math
pi=math.pi
print pi
print math.pi


3.14159265359
3.14159265359

In [61]:
pi=float('{:.5e}'.format(math.pi))
pi


Out[61]:
3.14159

In [62]:
print('{:.5e}'.format(math.pi))


3.14159e+00

In [63]:
math.sqrt(81.0)


Out[63]:
9.0

In [64]:
import random
random.random()


Out[64]:
0.0945862259612531

In [65]:
random.choice(range(1,11))


Out[65]:
10

In [66]:
x=10
print(bin(x))
print x.bit_length()


0b1010
4

In [67]:
x=3.5
print x.as_integer_ratio()


(7, 2)

In [68]:
print int(x)


3

In [69]:
y=float(42)
print y


42.0

In [70]:
y.is_integer()


Out[70]:
True

In [71]:
y=5.5
y.is_integer()


Out[71]:
False

In [72]:
y.hex()


Out[72]:
'0x1.6000000000000p+2'

In [73]:
# generate a list of 5 random numbers fom 0 to 99
random.sample(xrange(0,100),5)


Out[73]:
[89, 27, 5, 32, 9]

In [74]:
[random.random() for _ in range(0, 10)]


Out[74]:
[0.4694909393401463,
 0.8117523446752263,
 0.08925862471428991,
 0.42978024428183925,
 0.1383368512821752,
 0.902871033923867,
 0.7335970567726874,
 0.9432641162606268,
 0.3103139315529797,
 0.8564313459358601]

In [75]:
x = [random.randint(0,1000) for _ in range(10)]
print x


[237, 353, 915, 913, 685, 764, 385, 717, 213, 76]

In [75]:


In [76]:
random.choice(x)


Out[76]:
237

In [77]:
print range(10)
print range(0,10)
print range(5,16)


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

Complex Numbers

Decleration

In [78]:
# this is a complex number - notice the number before the the imaginary number j
a = 1 + 1j

In [79]:
# this will not work since j is not defined. 
a = 1 + j


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-79-c47076667052> in <module>()
----> 1 a = 1 + j

NameError: name 'j' is not defined

In [82]:
b=1-2j

In [83]:
c=complex(1,3)
print c


(1+3j)
Arithmetic Operations on complex variables

In [84]:
a*b


Out[84]:
(3-1j)

In [85]:
a-3*b


Out[85]:
(-2+7j)

In [86]:
a/b


Out[86]:
(-0.2+0.6j)
Properties

In [87]:
print c
print c.conjugate()


(1+3j)
(1-3j)

In [88]:
c.real


Out[88]:
1.0

In [89]:
c.imag


Out[89]:
3.0

Lists

A Python list is a container that stores sequence of elements. These elements need not be the same type. You can have strings stored alongside integers and other lists and data types

Note: Python is zero-based indexing: it starts indexing (lists, strings, etc) at zero just like C/C++/Java


In [90]:
# declare a list without initilization
my_list = range(5,15) 
print my_list


[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

In [91]:
# list slicing - start from index 1 to index 3 inclusive
my_list[1:4]


Out[91]:
[6, 7, 8]

In [92]:
# empty list declaration so you can add elements to it
my_list = []

In [93]:
len(my_list)


Out[93]:
0

In [94]:
my_list.append(10)
my_list.append(20)
print my_list


[10, 20]

In [95]:
my_list.append([1,2,3])
print my_list


[10, 20, [1, 2, 3]]

In [96]:
print my_list[2][1]


2

In [97]:
print my_list[3]


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-97-a1824c453f99> in <module>()
----> 1 print my_list[3]

IndexError: list index out of range

In [98]:
# get the length of the list
print len(my_list)


3

In [99]:
my_list.insert(2,5)
print my_list


[10, 20, 5, [1, 2, 3]]

In [100]:
# insert 7 before index 9. Since the list is not big enough, 7 gets appended 
# to the end of the list
my_list.insert(9,7)
print my_list


[10, 20, 5, [1, 2, 3], 7]

In [101]:
# insert 9 before index 3
my_list.insert(3,9)
print my_list


[10, 20, 5, 9, [1, 2, 3], 7]

In [102]:
print len(my_list)


6

In [103]:
# access list elements directly by indexing the list
print my_list[0]
print my_list[1]
print my_list[2]


10
20
5

In [104]:
# remove the element at index 3 from the list 
my_list.pop(3)
print my_list


[10, 20, 5, [1, 2, 3], 7]

In [105]:
# remove the first occurence of 5 from the listmy_list.remove(5)
print my_list


[10, 20, 5, [1, 2, 3], 7]

In [106]:
# get the last element of the list
print my_list[-1]
# or 
print my_list[len(my_list)-1]


7
7

In [107]:
# sorting a list
my_list=['x', '1', 3, 'z', 'a']
my_list.sort()
print my_list
my_list.reverse()
print my_list


[3, '1', 'a', 'x', 'z']
['z', 'x', 'a', '1', 3]

In [108]:
# lists containing other lists
my_list1 = range(0,5)
my_list2 = range(6,10)
my_list3 = [my_list1, my_list2]
print my_list3
print len(my_list3)


[[0, 1, 2, 3, 4], [6, 7, 8, 9]]
2

In [109]:
print len(my_list3[1])


4

In [110]:
my_list3[0]


Out[110]:
[0, 1, 2, 3, 4]

In [111]:
print len(my_list3[0])


5

In [112]:
my_list3[1][2]


Out[112]:
8

In [145]:
M=[[1,2,3],
   [4,5,6],
   [7,8,9]]
print M


[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In [114]:
# put the 2nd column of M in a list
column = []
for row in M:
    column.append(row[1])
print column


[2, 5, 8]

In [116]:
# list comprehension - another way of extracting the 2nd column of M
column = [row[1] for row in M]
print column


[2, 5, 8]

In [117]:
# compute the transpose of the matrix M
[[row[i] for row in M] for i in range(3)]


Out[117]:
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

In [122]:
# get the diagonal elements of M
diag = [M[i][i] for i in [0, 1, 2]]
print diag


[1, 5, 9]

In [125]:
# we can do operations on the new list elements before populating the list
repeat_char = [c * 2 for c in 'spam']
print repeat_char
print ''.join(repeat_char)


['ss', 'pp', 'aa', 'mm']
ssppaamm

In [126]:
# build a list with another list as elements
[[x ** 2, x ** 3] for x in range(4)]


Out[126]:
[[0, 0], [1, 1], [4, 8], [9, 27]]

In [144]:
# build a list with an if statement
[[x, x/2, x*2] for x in range(-6, 7, 2) if x > 0]


Out[144]:
[[2, 1.0, 4], [4, 2.0, 8], [6, 3.0, 12]]

In [131]:
# does the same thing as above but more 
big_list = []

for x in range(-6,7,2):
    if x > 0:
        big_list.append([x, x/2, x*2])

print big_list


[[2, 1.0, 4], [4, 2.0, 8], [6, 3.0, 12]]

In [130]:
# does the same as above but lots of code
big_list = []

for x in range(-6,7,2):
    lil_list = []
    if x > 0:
        lil_list.append(x)
        lil_list.append(x/2)
        lil_list.append(x*2)
        big_list.append(lil_list)

print big_list


[[2, 1.0, 4], [4, 2.0, 8], [6, 3.0, 12]]

In [139]:
range(-6, 7, 2)


Out[139]:
[-6, -4, -2, 0, 2, 4, 6]

In [133]:
# this is a generator - we'll talk more about this in another lecture
G = (sum(row) for row in M)
print next(G)
print next(G)
print next(G)


6
15
24

In [134]:
map(sum, M)


Out[134]:
[6, 15, 24]

In [ ]:


In [ ]:

Here is how we loop though a list of random numbers

In [118]:
for rand_int in [random.random() for _ in range(0, 10)]:
    print rand_int


0.245471241371
0.501071651329
0.862965043547
0.980037979137
0.152978554695
0.939002847475
0.23700562621
0.21835311086
0.356146271746
0.14266722293
We can make the above statement easier to read and debug by assigning the list to a variable that we iterate through

In [119]:
random_integers = [random.random() for _ in range(0, 10)]
for random_int in random_integers:
    print random_int


0.162123943256
0.97202776167
0.0845062887511
0.152548478467
0.728828677501
0.245620136379
0.831698626331
0.279719932575
0.433759642956
0.540595757565

Note: for large lists, use xrange for iterating though the list and use range for creating the list.


In [120]:
random.sample(range(0,100),10)


Out[120]:
[25, 65, 17, 42, 37, 78, 34, 52, 62, 13]

In [121]:
# generate a list of integers from -5 to 9 by 2
range(-5,10,2)


Out[121]:
[-5, -3, -1, 1, 3, 5, 7, 9]

In [135]:
list1 = random.sample(range(0,100),10)

In [136]:
list1


Out[136]:
[16, 74, 6, 36, 90, 75, 40, 5, 59, 85]

In [137]:
sum(list1)/10


Out[137]:
48.6

In [138]:
range(-6, 7, 2)


Out[138]:
[-6, -4, -2, 0, 2, 4, 6]

In [ ]: