Basics of Python: Part II


Bikash Santra and Avisek Gupta

Indian Statistical Institute, Kolkata


6. Conditional statements: if-elif-else

In [1]:
# General structure

# if condition1:
#     statement(s)

# elif condition2:
#     statement(s)

# elif condition3:
#     statement(s)

# ...

# elif conditionN:
#     statement(s)

# else:
#     statement(s)
In [2]:
a1 = 5
a2 = 10

if a1 > a2:
    print('a1 is greater')
elif a1 < a2:
    print('a2 is greater')
elif False:
    print('Why not have another elif')
elif False:
    print('Although these elifs make absolutely no sense')
else:
    print('a1 and a2 are equal')
a2 is greater

Exercise 1: Write a program that takes an integer as input, and prints whether the number is odd or even.

In [3]:
x = int(input("Enter an integer:"))

if x % 2 :
    print(x, 'is odd')
else:
    print(x, 'is even')
Enter an integer:5
5 is odd

7. Python indentations

a) There are no braces {} in Python to demarcate blocks of code
b) Indentations (whitespaces) demarcate blocks of code
c) Changes in indentation mark where a block begins, and where it ends
d) A common convention: 4 spaces (or 1 tab, which the editor converts to 4 spaces)

In [4]:
a1 = 10
a2 = 20
a3 = 30

if a1 == 10:
    if a2 == 20:
        if a3 == 30:
            print('Yay')
        else:
            print('Nay')
    else:
        print('Nay...')
else:
    print('Nayyyy...')
Yay

8. Loops

In [5]:
# 1. for loops

# General Structure

# for variable in iterator:
#     statement(s)
In [6]:
# range(t) : goes from 0 to t-1

for i in range(6): # [0, 1, 2, 3, 4, 5]
    print(i)
0
1
2
3
4
5
In [7]:
# range(start, end)

for i in range(0,5+1):
    print(i)
0
1
2
3
4
5
In [8]:
for i in range(5,10):
    print(i)
5
6
7
8
9
In [9]:
# range(start, end, steps)
for i in range(0,10,2):
    print(i)
0
2
4
6
8
In [10]:
# Opposite step direction

for i in range(10,0,-2):
    print(i)
10
8
6
4
2
In [11]:
# Iterate over strings

str1 = 'abcdefg'

for i in str1:
    print(i)
a
b
c
d
e
f
g
In [12]:
# Iterate more explicitly:

str1 = 'abcdefg'

for i in range(len(str1)):
    print(i, str1[i])
0 a
1 b
2 c
3 d
4 e
5 f
6 g
In [13]:
# 2. while loops

# General Structure

# while condition:
#     statement(s)
In [14]:
i = 0

while i < 10:
    print(i)
    i += 2
0
2
4
6
8

9. break, continue

In [15]:
# break

i = 0
while 1:
    i += 1
    if i > 10:
        break
print(i)
11
In [16]:
# continue

i = 0
while 1:
    i += 1
    if i > 10:
        break
    elif i <= 10:
        continue
    print('something')
print(i)
11

10. Functions

In [17]:
# General Structure

# def functionName(argument1, argument2, argumentN):
#     statement(s)
#     return return1, return2, returnN

# You can also return nothing.
In [18]:
def even(n):
    if n % 2 == 0:
        is_even = True
    else:
        is_even = False
    return is_even

n1 = 4
print(even(n1))
n2 = 7
print(even(n2))
True
False
In [19]:
def even(n):
    return n % 2 == 0

n1 = 20
print(even(n1))
n2 = 13
print(even(n2))
True
False
In [20]:
def mad_calculator(n1, n2):
    return n1+n2, n1-n2, n1*n2, n1/n2, n1%n2, n1//n2, n1**n2

a1 = 10
a2 = 5
print(mad_calculator(a1, a2))

a3 = 20
a4 = 4
ret1, ret2, ret3, ret4, ret5, ret6, ret7 = mad_calculator(a3, a4)
print(ret1, ret2, ret3, ret4, ret5, ret6, ret7)
(15, 5, 50, 2.0, 0, 2, 100000)
24 16 80 5.0 0 5 160000
In [21]:
# Default Values

def power(x, p=1):
    return x**p

print(power(x=10))
print(power(p=10, x=3))
10
59049
In [22]:
# Default values MUST be filled from the right
def power(x=1, p):
    return x**p

print(power(10, 3))
  File "<ipython-input-22-fc05662a8312>", line 2
    def power(x=1, p):
             ^
SyntaxError: non-default argument follows default argument

Principles of Object Oriented Programming

a) Abstraction
b) Encapsulation
c) Inheritance
d) Polymorphism

11. Classes

In [23]:
# General Structure

# class className:
#     def function1():
#         statement(s)
#     def function2():
#         statement(s)
#     def functionN():
#         statement(s)

# className objectName
# objectName.function1()

# Constructor:
# def __init__():
#     statements(s)
In [24]:
class rectangle:
    
    def __init__(selfabc, length=0, width=0):
        selfabc.length = length
        selfabc.width = width
    
    def area(self123):
        return self123.length * self123.width
In [25]:
var_rect = rectangle(length=2, width=3)
print(var_rect.area())
var_rect = rectangle()
print(var_rect.area())
6
0
In [26]:
class cuboid(rectangle):
    
    def __init__(self, length=0, width=0, height=0):
        rectangle.__init__(self, length=length, width=width)
        self.height = height
    
    def volume(self):
        return self.height*self.area()
    
var_cuboid = cuboid(length=2, width=3, height=4)
print(var_cuboid.volume())
var_cuboid2 = cuboid(length=5, width=6, height=7)
print(var_cuboid2.volume())
24
210

12. Data Structures: Lists, Tuples, Sets and Dictionaries

12.1 List: Mutable array that can store any object

In [27]:
l1 = [2, 3.5, 'apple', False]
print(l1)
print(l1[0])
print(l1[2])
[2, 3.5, 'apple', False]
2
apple
In [28]:
l1 = [2, 3.5, 'apple', False]
l1.append('Five')
print(l1)
[2, 3.5, 'apple', False, 'Five']
In [29]:
l2 = [l1, 'Six']
print(l2)
[[2, 3.5, 'apple', False, 'Five'], 'Six']
In [30]:
l1 = [2, 3.5, 'apple', False, 'apple']
l1.remove('apple')
print(l1)
[2, 3.5, False, 'apple']
In [31]:
l1.insert(2, 'apple')
print(l1)
[2, 3.5, 'apple', False, 'apple']
In [32]:
l1 = [2, 3.5, 'apple', False, 'Five']
x = l1.pop()
print(x)
print(l1)
Five
[2, 3.5, 'apple', False]
In [33]:
l1 = [2, 3.5, 'apple', False, 'Five']
print(len(l1))
5
In [34]:
l1 = [2, 3.5, 'apple', False, 'Five']
print(l1.index('apple'))
2
In [35]:
l1 = [2, 3.5, 'apple', False, 'apple', 'Five', 'apple']
print(l1)
print(l1.count('apple'))
[2, 3.5, 'apple', False, 'apple', 'Five', 'apple']
3
In [36]:
l3 = [20, 3.5, 14, 5, 1]
print(l3)
l3.sort()
print(l3)
l3.reverse()
print(l3)
[20, 3.5, 14, 5, 1]
[1, 3.5, 5, 14, 20]
[20, 14, 5, 3.5, 1]

Copying Caution!

In [37]:
l1 = [1, 2, 3, 4]
l2 = l1
l2.append(5)
print(l2)
print(l1)

print('\n')
l3 = list(l1)
#l3 = l1[:]
l3.append(6)
print(l3)
print(l1)
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]


[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5]

12.2 Tuples: Immutable arrays that can store any object

In [38]:
t1 = (2, 3, 'banana')
print(t1)
(2, 3, 'banana')
In [39]:
print(t1[0])
2
In [40]:
t1[0] = 1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-a75f7beedda4> in <module>()
----> 1 t1[0] = 1

TypeError: 'tuple' object does not support item assignment

12.3 Set: No duplicates

In [41]:
s1 = set({1, 2, 2, 3, 4})
print(s1)
{1, 2, 3, 4}
In [42]:
s1 = set({1, 2, 2, 3, 'abc', 4.5, 2.0})
print(s1)
{1, 2, 3, 4.5, 'abc'}
In [43]:
l1 = [2, 5, 1, 9, 2, 4, 1, 5, 9, 2, 2, 2, 9, 1]
l2 = list(set(l1))
print(l2)
[1, 2, 4, 5, 9]

12.4 Dictionaries: Map keys to values

In [44]:
roll = {'harry':1, 'ron':2, 'hermione':3, 'hermione':'helo'}

print(roll['harry'])
print(roll['ron'])
print(roll['hermione'])
1
2
helo
In [45]:
names = {1: 'harry', 2:'ron', 3:'hermione'}

print(names[1])
print(names[2])
print(names[3])
harry
ron
hermione
In [46]:
wtf = {1:'bla', 'ahem':2, 'food':'yes', 47:0}

print(wtf['ahem'])
print(wtf[47])
print(wtf['food'])
2
0
yes
In [47]:
roll = {'harry':1, 'ron':2, 'hermione':3}
print(len(roll))
print(roll.keys())
k1, k2, k3 = roll.keys()
print(k1, k2, k3)
print(roll.values())
3
dict_keys(['harry', 'ron', 'hermione'])
harry ron hermione
dict_values([1, 2, 3])

Looping Time!

In [48]:
# Lists

l1 = [1, 2, 3, 4, 5]

for x in l1:
    print(x)
1
2
3
4
5
In [49]:
l1 = [1, 2, 3, 4, 5]

for x in range(len(l1)):
    print(x, l1[x])
0 1
1 2
2 3
3 4
4 5
In [50]:
l1 = [1, 2, 3, 4, 5]

for x, y in enumerate(l1):
    print(x, y)
0 1
1 2
2 3
3 4
4 5
In [51]:
# Tuples

t1 = ('a1', 'a2', 'a3', 'a4')
for x in t1:
    print(x)
a1
a2
a3
a4
In [52]:
# Dictionaries

d1 = {'key1': 'val1', 'key2':'val2', 'key3': 'val3'}
print(d1.items())

for k, v in d1.items():
    print(k, v)
dict_items([('key1', 'val1'), ('key2', 'val2'), ('key3', 'val3')])
key1 val1
key2 val2
key3 val3
In [53]:
# Similar thing for lists

l1 = ['a1', 'a2', 'a3']

for idx, val in enumerate(l1):
    print(idx, val)
0 a1
1 a2
2 a3
In [54]:
questions = ['name?', 'marks?', 'hobby?', 'something', 'nope']
answers = ['Student', "zero :'(", 'sleeeping ^_^']
for q, a in zip(questions, answers):
    print(q, a)
    
for i, (q, a) in enumerate(zip(questions, answers)):
    print(i, q, a)
name? Student
marks? zero :'(
hobby? sleeeping ^_^
0 name? Student
1 marks? zero :'(
2 hobby? sleeeping ^_^
In [55]:
# List comprehensions

w_letters = []
for letter in 'aword':
    w_letters.append(letter)
print(w_letters)
['a', 'w', 'o', 'r', 'd']
In [56]:
h_letters = [ letter for letter in 'aword' ]
print( h_letters)
['a', 'w', 'o', 'r', 'd']
In [57]:
# General structure

# [expression for item in list if condition]
In [58]:
h_letters = [ letter for letter in 'aword' if letter != 'o']
print(h_letters)
['a', 'w', 'r', 'd']
In [59]:
[2*i for i in range(10) if i != 5]
Out[59]:
[0, 2, 4, 6, 8, 12, 14, 16, 18]

13. File I/O

In [60]:
f1 = open('afile', 'w')

f1.write('zzzz... huh?\n')
f1.write('*cough cough*')

f1.close()
In [61]:
f1 = open('afile', 'r')

c1 = f1.readline()
print(c1)

f1.close()
zzzz... huh?

In [62]:
f1 = open('afile', 'r')

c1 = f1.read()
print(c1)

f1.close()
zzzz... huh?
*cough cough*
In [63]:
f1 = open('afile', 'r')

for c1 in f1:
    print(c1)

f1.close()
zzzz... huh?

*cough cough*

14. String functions

In [64]:
s1 = 'abcd'
s2 = 'defg'

print(s1)
print(s2)
print(s1+s2)

print(s1.upper())
print(len(s1))

s3 = '       this is a sentence       '
print(s3)
print(s3.strip())

l1 = (s3.strip()).split() # other arguments for split
print(l1)
s4 = ' '.join(l1)
print(s4)
abcd
defg
abcddefg
ABCD
4
       this is a sentence       
this is a sentence
['this', 'is', 'a', 'sentence']
this is a sentence

14. Regular functions

In [65]:
import re
s1 = 'this is a sentence'

print(re.findall('sentence', s1))

print(re.sub('a sentence', 'not a sentence?', s1))
['sentence']
this is not a sentence?