COP3990C - Python Programming


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


Out[16]:

Numbers

Arithmetic


In [17]:
123+321


Out[17]:
444

In [18]:
4*5.5


Out[18]:
22.0

Exponentiation: use **


In [19]:
2**5


Out[19]:
32

How long is the number?


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


Out[20]:
'256'

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


Out[21]:
3

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


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


Out[22]:
2

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


In [23]:
20/8.0


Out[23]:
2.5

In [24]:
20/8.0


Out[24]:
2.5

In [25]:
20//8.0


Out[25]:
2.0

In [26]:
20 % 8.0


Out[26]:
4.0

In [27]:
divmod(20,8.0)


Out[27]:
(2.0, 4.0)

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


3.14159265359

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


Out[29]:
3.14159

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


3.14159e+00

In [31]:
math.sqrt(81.0)


Out[31]:
9.0

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


Out[32]:
0.06570969355754475

In [33]:
random.choice([1,2,3,4,5,6,7,8,9,10])


Out[33]:
9

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


0b1010
4

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


(7, 2)

In [36]:
print int(x)


3

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


42.0

In [38]:
y.is_integer()


Out[38]:
True

In [39]:
y.hex()


Out[39]:
'0x1.5000000000000p+5'

In [40]:
random.sample(xrange(0,100),10)


Out[40]:
[27, 44, 30, 54, 42, 24, 19, 23, 33, 8]

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


Out[41]:
[0.04222760370113021,
 0.7778377807222588,
 0.03492429524189766,
 0.6911220844818712,
 0.543062885040173,
 0.7834990727933138,
 0.8254433703804843,
 0.9252933726298425,
 0.43867412042221055,
 0.5563190396124577]

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


[435, 606, 439, 266, 622, 201, 114, 154, 352, 97]

In [43]:
random.choice(x)


Out[43]:
154

Complex Numbers

Decleration


In [44]:
a=1+1j

In [45]:
b=1-2j

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


(1+3j)

Arithmetic Operations


In [47]:
a*b


Out[47]:
(3-1j)

In [48]:
a-3*b


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

In [49]:
a/b


Out[49]:
(-0.2+0.6j)

Properties


In [50]:
c.conjugate()


Out[50]:
(1-3j)

In [51]:
c.real


Out[51]:
1.0

In [52]:
c.imag


Out[52]:
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 [53]:
# declare a list without initilization
my_list = range(0,10) 
print my_list


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

In [54]:
# list slicing - 
my_list[1:4]


Out[54]:
[1, 2, 3]

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

In [56]:
my_list.append(1)
my_list.append(2)
print my_list


[1, 2]

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


2

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


[1, 2, 5]

In [59]:
# 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


[1, 2, 5, 7]

In [60]:
# insert 9 before index 3, which has the value 7
my_list.insert(3,9)
print my_list


[1, 2, 5, 9, 7]

In [61]:
print len(my_list)


5

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


1
2
5

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


[1, 2, 5, 7]

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


[1, 2, 7]

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


7
7

In [66]:
# 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 [67]:
# 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 [68]:
my_list3[0]


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

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


5

In [70]:
my_list3[1][2]


Out[70]:
8

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


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

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


[2, 5, 8]

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


[2, 5, 8]

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


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

Here is how we loop though a list of random numbers


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


0.383861497126
0.625777084656
0.617462039753
0.862742483535
0.412783524082
0.429756575422
0.751974435714
0.72631220327
0.297007839706
0.27180427525

We can make the above statement easier to read and debug by assigning the list to a variable that we iterate through


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


0.0401268325241
0.14303556831
0.940657436755
0.0688121904838
0.518564853937
0.0161053020645
0.63548896765
0.998279944091
0.247358240368
0.301949665676

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


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


Out[77]:
[43, 33, 31, 9, 89, 77, 59, 3, 61, 14]

Strings


In [78]:
# create a string
str = '   the quick brown fox jumps over the lazy dog. '
str


Out[78]:
'   the quick brown fox jumps over the lazy dog. '

In [79]:
# this is an empty string
empty_str = ''

In [160]:
# strip whitespaces from the beginning and ending of the string
str2=str.strip()
str2


Out[160]:
'the quick brown fox jumps over the lazy dog.'

In [81]:
# this capitalizes the 1st letter of the string
str2.capitalize()


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-81-54483805149a> in <module>()
      1 # this capitalizes the 1st letter of the string
----> 2 str2.capitalize()

NameError: name 'str2' is not defined

In [82]:
# count the number of occurrences for the string o
str.count('o')


Out[82]:
4

In [83]:
# check if a string ends with a certain character
str2.endswith('.')


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-83-ce971681ca5a> in <module>()
      1 # check if a string ends with a certain character
----> 2 str2.endswith('.')

NameError: name 'str2' is not defined

In [84]:
# check if a substring exists in the string
'fox' in str


Out[84]:
True

In [85]:
# find the index of the first occurrence  
str.find('fox')


Out[85]:
19

In [86]:
# let's see what character is at index 19
str[19]


Out[86]:
'f'
Lists and Strings

Note: strings are immutable while lists are not. In other words immutability does not allow for in-place modification of the object.

"Also notice in the prior examples that we were not changing the original string with any of the operations we ran on it. Every string operation is defined to produce a new string as its result, because strings are immutable in Python—they cannot be chang ed in place after they are created. In other words, you can never overwrite the values of immutable objects. For example, you can’t change a string by assigning to one of its positions, but you can always build a new one and assign it to the same name. Because Python cleans up old objects as you go (as you’ll see later), this isn’t as inefficient as it may sound:"


In [87]:
S = 'shrubbery' 
S[1]='c'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-87-b22ad8005f58> in <module>()
      1 S = 'shrubbery'
----> 2 S[1]='c'

TypeError: 'str' object does not support item assignment


In [88]:
S = 'shrubbery' 
L = list(S)
L


Out[88]:
['s', 'h', 'r', 'u', 'b', 'b', 'e', 'r', 'y']

In [89]:
L[1] = 'c'
print L
print ''.join(L)


['s', 'c', 'r', 'u', 'b', 'b', 'e', 'r', 'y']
scrubbery

In [90]:
# another way of changing the string 
S = S[0] + 'c' + S[2:] # string concatenation
S


Out[90]:
'scrubbery'

In [91]:
# 
line = 'aaa,bbb,cccc c,dd'
line1 = line.split(',') 
print line
print line1


aaa,bbb,cccc c,dd
['aaa', 'bbb', 'cccc c', 'dd']

In [91]: