3_Intro_to_Python
June 22, 2018
In [1]: import im_show_mod
im_show_mod.showImage('./img/logo.png', 160,55)
1 Using Python as a Calculator
• Numbers - operators +, -, * and /, parentheses (()) can be used for grouping
In [1]: 3+6
Out[1]: 9
In [2]: (50 - 5*6) / 4
Out[2]: 5.0
• Division (/) always returns a float. To do floor division and get an integer result (discarding
any fractional result) you can use the // operator.
• To calculate the remainder you can use %:
In [3]: 17 / 3
Out[3]: 5.666666666666667
1
In [4]: 17 // 3
Out[4]: 5
In [5]: width = 20
print(width)
height = 5 * 9
print("height " ,height)
print(width * height)
20
height 45
900
• Strings - Python can also manipulate strings, which can be expressed in several ways. They
can be enclosed in single quotes (’...’) or double quotes ("...") with the same result. The
character ” can be used to escape single/double quotes
In [6]: "sam's eggs"
Out[6]: "sam's eggs"
In [7]: s = 'First line.\tSecond line.'
In [8]: s
Out[8]: 'First line.\tSecond line.'
In [9]: print(s)
First line. Second line.
In [10]: print( 'First line.\tSecond line.')
First line. Second line.
• Strings can be concatenated (glued together) with the + operator, and repeated with *:
In [11]: 5*'un' + 'ited'
Out[11]: 'unununununited'
• Two or more string literals (i.e. the ones enclosed between quotes) next to each other are
automatically concatenated.
In [12]: a = 'Py' 'thon'
print(a)
2
Python
• Strings can be indexed (subscripted), with the first character having index 0.
In [13]: word = 'Python'
In [14]: word[0]
Out[14]: 'P'
In [15]: word[5]
Out[15]: 'n'
• Indices may also be negative numbers, to start counting from the right
In [16]: word[-1]
Out[16]: 'n'
In [17]: word[-6]
Out[17]: 'P'
In [18]: word[: :-1]
Out[18]: 'nohtyP'
• String Slicing : While indexing is used to obtain individual characters, slicing allows you
to obtain substring
In [19]: word[2:4]
Out[19]: 'th'
• Note how the start is always included, and the end always excluded.
• This makes sure that s[:i] + s[i:] is always equal to s
In [20]: word[ :4] + word[4: ]
Out[20]: 'Python'
• String Slice/Index - "string index out of range" error
In [21]: #word[20]
In [22]: word[20:21]
Out[22]: ''
In [23]: word[:]
3
Out[23]: 'Python'
In [24]: word[40:]
Out[24]: ''
In [25]: 'J'+word[1:]
Out[25]: 'Jython'
In [26]: len(word)
Out[26]: 6
2 Compound Types
• List - Python knows a number of compound data types, used to group together other values.
The most versatile is the list, which can be written as a list of comma-separated values (items)
between square brackets. Lists might contain items of different types, but usually the items
all have the same type.
In [27]: squares = [1, 4, 9, 16, 25, 'kalam']
In [28]: squares[5]
Out[28]: 'kalam'
In [29]: squares[-4]
Out[29]: 9
In [30]: squares[1:3]
Out[30]: [4, 9]
In [31]: squares[:]
Out[31]: [1, 4, 9, 16, 25, 'kalam']
• Lists also support operations like concatenation:
In [32]: squares + [36, 49, 64, 81, 100, 121]
Out[32]: [1, 4, 9, 16, 25, 'kalam', 36, 49, 64, 81, 100, 121]
• Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change
their content
In [81]: word[2] = 'o'
4
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-81-f1cfd6650c99> in <module>()
----> 1 word[2] = 'o'
TypeError: 'str' object does not support item assignment
In [34]: cubes = [1, 8, 27, 65, 125]
In [35]: cubes[3] = 4**3
In [36]: cubes
Out[36]: [1, 8, 27, 64, 125]
• List append() method:You can also add new items at the end of the list, by using the ap-
pend() method
In [37]: cubes.append(216)
cubes.append(7 ** 3)
In [38]: cubes
Out[38]: [1, 8, 27, 64, 125, 216, 343]
• Assignment to slices is also possible, and this can even change the size of the list or clear it
entirely
In [39]: letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
In [40]: letters
Out[40]: ['a', 'b', 'c', 'd', 'e', 'f', 'g']
In [41]: letters[2:4]
Out[41]: ['c', 'd']
In [42]: letters[2:4] = ['C', 'D', 'E']
letters
Out[42]: ['a', 'b', 'C', 'D', 'E', 'e', 'f', 'g']
In [43]: letters[2:5] = []
letters
5
Out[43]: ['a', 'b', 'e', 'f', 'g']
In [44]: letters[:]
Out[44]: ['a', 'b', 'e', 'f', 'g']
In [45]: letters[:] = []
In [46]: letters
Out[46]: []
In [47]: letters = ['a', 'b', 'c', 'd']
len(letters)
Out[47]: 4
• Nesting Lists It is possible to nest lists (create lists containing other lists)
In [48]: a = ['a', 'b', 'c']
n = [1, 2, 3]
x = [a, n]
x
Out[48]: [['a', 'b', 'c'], [1, 2, 3]]
In [49]: x[1][1]
Out[49]: 2
3 Control Flow Tools - First Steps Towards Programming
In [50]: a, b = 0, 1 #multiple assignment
while b < 10:
print(b)
a, b = b, a+b #multiple assignment
print(a,b)
1
1
2
3
5
8
8 13
• if statement
6
In [51]: x = int(input('Please Enter an Integer : '))
if x < 0:
x = 0
print('---- Negetive changed to zero')
elif x == 0:
print('---- Zero')
elif x == 1:
print('---- One')
else:
print('---- Other Number')
Please Enter an Integer : 1
---- One
• for statement
In [52]: words = ['cat', 'window', 'doorstopper']
for x in words:
print(x)
cat
window
doorstopper
• Update the list while looping, need to copy or make a slice
In [53]: print(words)
['cat', 'window', 'doorstopper']
In [54]: for x in words[:] :
if len(x) > 6:
words.insert(0, x)
print(words)
['doorstopper', 'cat', 'window', 'doorstopper']
• range() function
In [55]: print(range(10))
range(0, 10)
In [56]: for i in range(10):
print(i)
7
0
1
2
3
4
5
6
7
8
9
In [57]: for i in range(0,15,3):
print(i)
0
3
6
9
12
In [58]: i = 0
while i < 10:
print(i)
i = i+1
0
1
2
3
4
5
6
7
8
9
In [59]: words = ['cat', 'window', 'doorstoper']
In [60]: print(len(words))
In [61]: for i in range(len(words)):
print(i, words[i])
8
0 cat
1 window
2 doorstoper
• break statement
• Loop statements may have an else clause; it is executed when the loop terminates through
exhaustion of the list (with for) or when the condition becomes false (with while), but not
when the loop is terminated by a break statement. This is exemplified by the following loop,
which searches for prime numbers
In [62]: for i in range(2,10):
print(i)
2
3
4
5
6
7
8
9
In [63]: for i in range(2,2):
print(i)
In [64]: for n in range(2, 10):
flag = True
for x in range(2, n):
if n % x == 0:
flag = False
break
if(flag):
print(n, 'is a prime number')
2 is a prime number
3 is a prime number
5 is a prime number
7 is a prime number
In [65]: for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
#print(n, 'equals', x, '*', n//x)
break
else:
print(n, 'is a prime number')
9
2 is a prime number
3 is a prime number
5 is a prime number
7 is a prime number
• continue statement
In [66]: #num = 0
for num in range(2, 10):
i = 10
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
print("New String")
print("i : ", i)
print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
New String
i : 10
Found a number 9
• pass statement
• The pass statement does nothing. It can be used when a statement is required syntactically
but the program requires no action.
In [67]: #This is commonly used for creating minimal classes:
class MyEmptyClass:
pass
In [68]: def simpleMethod(var1, var2, var3):
print("Simple Method Printing : ", var1)
print("Simple {0} Method {1} Printing : {2} ".format(var1, var2, var3))
In [69]: simpleMethod(6, 'eds', 'xyz')
Simple Method Printing : 6
Simple 6 Method eds Printing : xyz
10
In [70]: def starArgs(*vals):
print('inside : ', type(vals))
for x in vals:
print(x)
In [71]: lst = ['rama', 'gopal', 'madan', 'krishna']
starArgs(10, lst, 123, 8, 9,9,1221,990)
inside : <class 'tuple'>
10
['rama', 'gopal', 'madan', 'krishna']
123
8
9
9
1221
990
In [72]: #Another place pass can be used is as a place-holder for a function or conditional body
#working on new code, allowing you to keep thinking at a more abstract level. The pass
def initLogs(*args):
pass # Remember to implement this!
In [73]: def fib(n = 100): # write Fibonacci series up to n
"""Print a Fibonacci series up to n."""
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
In [74]: febs = fib(800)
febs
Out[74]: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
• del statement
In [75]: a = [-1, 1, 66.25, 333, 333, 1234.5]
del a[0]
In [76]: a
Out[76]: [1, 66.25, 333, 333, 1234.5]
In [77]: del a[0], a[3]
11
In [78]: a
Out[78]: [66.25, 333, 333]
• Tuples and Sequences Tuples are immutable, and usually contain a heterogeneous sequence
of elements
In [79]: t = 12345, 22912, 'example' #is an example of tuple packing
print(t)
print(len(t))
t[1]
(12345, 22912, 'example')
3
Out[79]: 22912
In [80]: t[1] = 6666
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-80-73b0c0b20a0f> in <module>()
----> 1 t[1] = 6666
TypeError: 'tuple' object does not support item assignment
In [ ]: x, y, z = t # Sequence unpacking and works for any sequence on the right-hand side
x
In [ ]: t[0:2]
4 Sets
• A set is an unordered collection with no duplicate elements. Basic uses include membership
testing and eliminating duplicate entries. Set objects also support mathematical operations
like union, intersection, difference, and symmetric difference.
In [ ]: emptySet = set() # not {}
basket = {'apple', 23, 'orange', 'apple', 'pear', 'orange', 'banana'}
basket1 = {'kfjskjf', 'kldsjflksf'}
print(basket)
12
In [ ]: a = set('abrac adabra')
b = set('alacazam')
a # unique letters in a
In [ ]: b # unique letters in b
In [ ]: a - b # letters in a but not in b
In [ ]: a | b # letters in either a or b
In [ ]: a & b # letters in both a and b
In [ ]: a ^ b # letters in a or b but not both
In [ ]: # Similarly to list comprehensions, set comprehensions are also supported
a = {x for x in {1,2,3,4,5,6,7} if x not in [1,2,3]}
a
In [ ]: for x in {1,2,3,4,5,6,7}:
present = False
for y in [1,2,3]:
if (x == y):
present = True
break
if (not present):
print(x)
5 Dictionaries
• Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by
keys, which can be any immutable type; strings and numbers can always be keys
In [ ]: lst = [2,4,5]
lst[2] = 99
lst
In [ ]: tel = {'jack': 4098, 'sape': 4139}
type(tel)
In [ ]: tel['mango'] = 4127
tel
In [ ]: tel['jack']
In [ ]: tel['jack'] = 2222
print(tel)
In [ ]: del tel['sape']
In [ ]: tel
13
In [ ]: tel['irv'] = 4127
In [ ]: type(tel)
In [ ]: tel.keys()
In [ ]: list(tel.keys())
In [ ]: for k in tel.keys():
print(tel[k])
In [ ]: sorted(tel, key = lambda x: x[1])
In [ ]: 'mango' in tel
In [ ]: 'jack' not in tel
• The dict() constructor builds dictionaries directly from sequences of key-value pairs.
In [ ]: dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
In [ ]: dict(sape=4139, guido=4127, jack=4098)
• dict comprehensions can be used to create dictionaries from arbitrary key and value expres-
sions
In [ ]: squares = {x:x**2 for x in (2, 4, 6)}
In [ ]: squares
In [ ]: squares[4]
In [ ]: knights = {'vikram': 'the pure', 'kala': 'the brave'}
for k, v in knights.items():
print(k, ':', v)
enumerate() function
• When looping through a sequence, the position index and corresponding value can be re-
trieved at the same time using the enumerate() function.
In [ ]: lst = [13,18,20]
for i in range(len(lst)):
print(i, lst[i])
In [ ]: for i, v in enumerate({'tic', 'tac', 'toe'}):
print(i, v)
14
zip() function
• To loop over two or more sequences at the same time, the entries can be paired with the zip()
function.
In [ ]: questions = ['name', 'quest', 'favorite color']
answers = ['Vikram', 'the holy grail']
answers2 = ['Vikram2', 'the holy grail2', 'blue2']
for q, a, a2 in zip(questions, answers, answers2):
print(q, '-', a, '-', a2)
In [ ]: zp = zip(questions, answers, answers2)
print(list(zp))
* Keyword Arguments When a final formal parameter of the form ****name is present, it
receives a dictionary containing all keyword arguments except for those corresponding to a
formal parameter. This may be combined with a formal parameter of the form *name which
receives a tuple containing the positional arguments beyond the formal parameter list. name
must occur before name. For example, if we define a function like this:
In [ ]: def cheeseshop(kind, *arguments, **keywords):
print("Q) Do you have any", kind, "?")
print("Ans) I'm sorry, we're all out of", kind)
print(type(arguments))
for arg in arguments:
print(arg)
print("-" * 40)
print(type(keywords))
for kw in keywords:
print(kw, ":", keywords[kw])
In [ ]: cheeseshop("Cheese",
"Fresh Cheese",
"Good Cheese is sold here",
shopkeeper="Chandra",
client="Rama Rao",
sketch="Cheese Shop Sketch",
sketch1="Cheese Shop Sketch",
sketch2="Cheese Shop Sketch")
5.0.1 API Documentation reference : https://docs.python.org/3/library/index.html
5.0.2 Language reference : https://docs.python.org/3/reference/index.html
In [ ]: def createDict(lst):
dict1 = dict()
for x in lst:
if x in dict1:
dict1[x] = dict1[x] + 1
15
else:
dict1[x] = 1
return dict1
def annagrom(s1, s2):
s1 = s1.lower()
s2 = s2.lower()
if(len(s1) == len(s2)):
lst1 = list(s1)
print('list from word 1', lst1)
lst2 = list(s2)
print('list from word 2', lst1)
dict1 = createDict(lst1)
print('dict1 - letter counts - ', dict1)
dict2 = createDict(lst2)
print('dict2 - letter counts - ', dict2)
if dict1 == dict2:
return True
else:
return False
else:
return False
In [ ]: output = annagrom('aiikda', 'andiai')
print(output)
In [ ]: list('aiinda')
16