Bikash Santra and Avisek Gupta
Indian Statistical Institute, Kolkata
# General structure
# if condition1:
# statement(s)
# elif condition2:
# statement(s)
# elif condition3:
# statement(s)
# ...
# elif conditionN:
# statement(s)
# else:
# statement(s)
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')
Exercise 1: Write a program that takes an integer as input, and prints whether the number is odd or even.
x = int(input("Enter an integer:"))
if x % 2 :
print(x, 'is odd')
else:
print(x, 'is even')
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)
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...')
# 1. for loops
# General Structure
# for variable in iterator:
# statement(s)
# range(t) : goes from 0 to t-1
for i in range(6): # [0, 1, 2, 3, 4, 5]
print(i)
# range(start, end)
for i in range(0,5+1):
print(i)
for i in range(5,10):
print(i)
# range(start, end, steps)
for i in range(0,10,2):
print(i)
# Opposite step direction
for i in range(10,0,-2):
print(i)
# Iterate over strings
str1 = 'abcdefg'
for i in str1:
print(i)
# Iterate more explicitly:
str1 = 'abcdefg'
for i in range(len(str1)):
print(i, str1[i])
# 2. while loops
# General Structure
# while condition:
# statement(s)
i = 0
while i < 10:
print(i)
i += 2
# break
i = 0
while 1:
i += 1
if i > 10:
break
print(i)
# continue
i = 0
while 1:
i += 1
if i > 10:
break
elif i <= 10:
continue
print('something')
print(i)
# General Structure
# def functionName(argument1, argument2, argumentN):
# statement(s)
# return return1, return2, returnN
# You can also return nothing.
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))
def even(n):
return n % 2 == 0
n1 = 20
print(even(n1))
n2 = 13
print(even(n2))
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)
# Default Values
def power(x, p=1):
return x**p
print(power(x=10))
print(power(p=10, x=3))
# Default values MUST be filled from the right
def power(x=1, p):
return x**p
print(power(10, 3))
a) Abstraction
b) Encapsulation
c) Inheritance
d) Polymorphism
# 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)
class rectangle:
def __init__(selfabc, length=0, width=0):
selfabc.length = length
selfabc.width = width
def area(self123):
return self123.length * self123.width
var_rect = rectangle(length=2, width=3)
print(var_rect.area())
var_rect = rectangle()
print(var_rect.area())
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())
l1 = [2, 3.5, 'apple', False]
print(l1)
print(l1[0])
print(l1[2])
l1 = [2, 3.5, 'apple', False]
l1.append('Five')
print(l1)
l2 = [l1, 'Six']
print(l2)
l1 = [2, 3.5, 'apple', False, 'apple']
l1.remove('apple')
print(l1)
l1.insert(2, 'apple')
print(l1)
l1 = [2, 3.5, 'apple', False, 'Five']
x = l1.pop()
print(x)
print(l1)
l1 = [2, 3.5, 'apple', False, 'Five']
print(len(l1))
l1 = [2, 3.5, 'apple', False, 'Five']
print(l1.index('apple'))
l1 = [2, 3.5, 'apple', False, 'apple', 'Five', 'apple']
print(l1)
print(l1.count('apple'))
l3 = [20, 3.5, 14, 5, 1]
print(l3)
l3.sort()
print(l3)
l3.reverse()
print(l3)
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)
t1 = (2, 3, 'banana')
print(t1)
print(t1[0])
t1[0] = 1
s1 = set({1, 2, 2, 3, 4})
print(s1)
s1 = set({1, 2, 2, 3, 'abc', 4.5, 2.0})
print(s1)
l1 = [2, 5, 1, 9, 2, 4, 1, 5, 9, 2, 2, 2, 9, 1]
l2 = list(set(l1))
print(l2)
roll = {'harry':1, 'ron':2, 'hermione':3, 'hermione':'helo'}
print(roll['harry'])
print(roll['ron'])
print(roll['hermione'])
names = {1: 'harry', 2:'ron', 3:'hermione'}
print(names[1])
print(names[2])
print(names[3])
wtf = {1:'bla', 'ahem':2, 'food':'yes', 47:0}
print(wtf['ahem'])
print(wtf[47])
print(wtf['food'])
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())
# Lists
l1 = [1, 2, 3, 4, 5]
for x in l1:
print(x)
l1 = [1, 2, 3, 4, 5]
for x in range(len(l1)):
print(x, l1[x])
l1 = [1, 2, 3, 4, 5]
for x, y in enumerate(l1):
print(x, y)
# Tuples
t1 = ('a1', 'a2', 'a3', 'a4')
for x in t1:
print(x)
# Dictionaries
d1 = {'key1': 'val1', 'key2':'val2', 'key3': 'val3'}
print(d1.items())
for k, v in d1.items():
print(k, v)
# Similar thing for lists
l1 = ['a1', 'a2', 'a3']
for idx, val in enumerate(l1):
print(idx, val)
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)
# List comprehensions
w_letters = []
for letter in 'aword':
w_letters.append(letter)
print(w_letters)
h_letters = [ letter for letter in 'aword' ]
print( h_letters)
# General structure
# [expression for item in list if condition]
h_letters = [ letter for letter in 'aword' if letter != 'o']
print(h_letters)
[2*i for i in range(10) if i != 5]
f1 = open('afile', 'w')
f1.write('zzzz... huh?\n')
f1.write('*cough cough*')
f1.close()
f1 = open('afile', 'r')
c1 = f1.readline()
print(c1)
f1.close()
f1 = open('afile', 'r')
c1 = f1.read()
print(c1)
f1.close()
f1 = open('afile', 'r')
for c1 in f1:
print(c1)
f1.close()
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)
import re
s1 = 'this is a sentence'
print(re.findall('sentence', s1))
print(re.sub('a sentence', 'not a sentence?', s1))