
Bikash Santra
Indian Statistical Institute, Kolkata
# General structure
# if result of condition1:
# statement(s)
# elif condition2:
# statement(s)
# elif condition3:
# statement(s)
# ...
# elif conditionN:
# statement(s)
# else:
# statement(s)
a1 = 7
a2 = 7
if a1 > a2:
print('a1 is greater')
x,y = 5,5
y += x
print(x, y)
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')
print('I am out of the if sdtatem,ent')
a1 and a2 are equal I am out of the if sdtatem,ent
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')
Enter an integer:12 12 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...')
Yay
inp = input('Please enter two numbers')
Please enter two numbers12 34
print(inp, type(inp), inp.split())
a, b = inp.split()
print(int(a), int(b), type(a), type(b))
12 34 <class 'str'> ['12', '34'] 12 34 <class 'str'> <class 'str'>
# 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]
# if i != 0:
print(i**2)
0 1 4 9 16 25
# range(start, end)
for i in range(2, 7+1):
print(i)
2 3 4 5 6 7
for i in range(5,10):
print(i)
5 6 7 8 9
# range(start, end, steps)
for i in range(21,100,3):
print(i)
21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99
# Opposite step direction
#### FORWARD DIRECTION
for i in range(0,10,2):
print(i)
print('\n')
#### BACKWARD DIRECTION
for i in range(8,-1,-2):
print(i)
0 2 4 6 8 8 6 4 2 0
# Iterate over strings
str1 = 'abcdefg hijk'
for i in str1:
print(i)
a b c d e f g h i j k
# Iterate more explicitly:
str1 = 'abcdefg'
print(str1[6])
g
for i in range(len(str1)):
print(i+1, str1[i])
1 a 2 b 3 c 4 d 5 e 6 f 7 g
# 2. while loops
# General Structure
# while condition:
# statement(s)
i = 0
while i <= 24:
print(i)
i += 4
0 4 8 12 16 20 24
Exercise: Do these programs using for and while loops both 1) Write a program to print the odd integers upto 10,000.
2) Then break the loop when the odd number is greater than 1000.
i = 0
while i <= 10000:
if i>1000:
break;
if i%2!=0:
print(i)
i += 1
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 101 103 105 107 109 111 113 115 117 119 121 123 125 127 129 131 133 135 137 139 141 143 145 147 149 151 153 155 157 159 161 163 165 167 169 171 173 175 177 179 181 183 185 187 189 191 193 195 197 199 201 203 205 207 209 211 213 215 217 219 221 223 225 227 229 231 233 235 237 239 241 243 245 247 249 251 253 255 257 259 261 263 265 267 269 271 273 275 277 279 281 283 285 287 289 291 293 295 297 299 301 303 305 307 309 311 313 315 317 319 321 323 325 327 329 331 333 335 337 339 341 343 345 347 349 351 353 355 357 359 361 363 365 367 369 371 373 375 377 379 381 383 385 387 389 391 393 395 397 399 401 403 405 407 409 411 413 415 417 419 421 423 425 427 429 431 433 435 437 439 441 443 445 447 449 451 453 455 457 459 461 463 465 467 469 471 473 475 477 479 481 483 485 487 489 491 493 495 497 499 501 503 505 507 509 511 513 515 517 519 521 523 525 527 529 531 533 535 537 539 541 543 545 547 549 551 553 555 557 559 561 563 565 567 569 571 573 575 577 579 581 583 585 587 589 591 593 595 597 599 601 603 605 607 609 611 613 615 617 619 621 623 625 627 629 631 633 635 637 639 641 643 645 647 649 651 653 655 657 659 661 663 665 667 669 671 673 675 677 679 681 683 685 687 689 691 693 695 697 699 701 703 705 707 709 711 713 715 717 719 721 723 725 727 729 731 733 735 737 739 741 743 745 747 749 751 753 755 757 759 761 763 765 767 769 771 773 775 777 779 781 783 785 787 789 791 793 795 797 799 801 803 805 807 809 811 813 815 817 819 821 823 825 827 829 831 833 835 837 839 841 843 845 847 849 851 853 855 857 859 861 863 865 867 869 871 873 875 877 879 881 883 885 887 889 891 893 895 897 899 901 903 905 907 909 911 913 915 917 919 921 923 925 927 929 931 933 935 937 939 941 943 945 947 949 951 953 955 957 959 961 963 965 967 969 971 973 975 977 979 981 983 985 987 989 991 993 995 997 999
# break
i = 0
while 1:
print(i)
i += 1
if i > 10:
break
print(i)
0 1 2 3 4 5 6 7 8 9 10 11
for i in range(15):
print(i)
if i > 10:
break
0 1 2 3 4 5 6 7 8 9 10 11
# continue
i = 0
while 1:
# continue
i += 1
if i > 10:
break
elif i <= 10:
continue
print('something')
print(i)
11
Excercise: press 1 for add, 2 for division, 3 for multiplication, 4 for substraction
user asks that I want to execute add/division
l1 = [2, 3.5, 'apple', False]
print(l1, type(l1))
[2, 3.5, 'apple', False] <class 'list'>
print(l1)
[2, 3.5, 'apple', False]
print(l1[2])
apple
print(l1[3])
False
l1.append('Five')
print(l1)
[2, 3.5, 'apple', False, 'Five']
l2 = [l1, 'Six']
print(l2)
[[2, 3.5, 'apple', False, 'Five'], 'Six']
l1 = [2, 3.5, 'apple', False, 'apple']
l1.remove('apple')
print(l1)
[2, 3.5, False, 'apple']
l1.insert(3, False)
print(l1)
[2, 3.5, False, False, 'apple']
l1 = [2, 3.5, 'apple', False, 'Five']
x = l1.pop()
print(x)
print(l1)
Five [2, 3.5, 'apple', False]
l1 = [2, 3.5, 'apple', False, 'Five']
print(len('apple'), len(l1))
5 5
l1 = [2, 3.5, 'apple', False, 'Five', 'apple']
print(l1.index('apple'))
2
l1 = [2, 3.5, 'apple', False, 'apple', 'Five', 'apple']
print(l1)
print(l1.count('apple'))
[2, 3.5, 'apple', False, 'apple', 'Five', 'apple'] 3
l3 = [20, 3.5, 14, 5, 1]
print(l3)
# l4 = list.sort(l3)
# print(l4)
[20, 3.5, 14, 5, 1]
l3.sort()
print(l3)
[1, 3.5, 5, 14, 20]
l3.reverse()
print(l3)
[20, 14, 5, 3.5, 1]
l1 = l3.copy()
print(l1)
[20, 14, 5, 3.5, 1]
l3.reverse()
print(l3)
[1, 3.5, 5, 14, 20]
print(l1)
[20, 14, 5, 3.5, 1]
l1.reverse()
print(l1)
[1, 3.5, 5, 14, 20]
print(l3)
[1, 3.5, 5, 14, 20]
l1 = [1, 2, 3, 4]
l2 = l1
l2.append(5)
print(l2)
[1, 2, 3, 4, 5]
print(l1)
[1, 2, 3, 4, 5]
l1.append(6)
print(l2,l1)
[1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]
# print('\n')
l3 = list(l1)
#l3 = l1[:]
l3.append(6)
print(l3)
print(l1)
[1, 2, 3, 4, 5, 6, 6] [1, 2, 3, 4, 5, 6]
t1 = (2, 3, 'banana')
print(t1)
(2, 3, 'banana')
t2=(2,3)
print(t2, type(t2))
(2, 3) <class 'tuple'>
ll1 = [t1, 5, False]
print(ll1)
[(2, 3, 'banana'), 5, False]
print(t1[0], type(t1[0]))
2 <class 'int'>
ll1[0] = 1
print(ll1)
[1, 5, False]
t1 = (2, 3, ['banana'])
print(t1)
t1[2][0] = 5
print(t1)
(2, 3, ['banana']) (2, 3, [5])
t3 = list(t1)
print(t3)
[2, 3, [5]]
s1 = set({1, 2, 2, 3, 4})
print(s1)
{1, 2, 3, 4}
s1 = set({1, 2, 2, 3, 'abc', 4.5, 2.0})
print(s1)
{1, 2, 3, 4.5, 'abc'}
l1 = [2, 5, 1, 9, 2, 4, 1, 5, 9, 2, 2, 2, 9, 1]
print(set(l1))
{1, 2, 4, 5, 9}
l2 = list(set(l1))
print(l2)
[1, 2, 4, 5, 9]
roll = {'harry':1, 'ron':2, 'hermione':3, 'hermione':'helo'}
# roll = {'PGDSMA01':'Mr. XXXX', 'PGDSMA01':'Mr.YYYY', 'PGDSMA02':'Mr. XXXX', 44:True}
print(roll)
{'harry': 1, 'ron': 2, 'hermione': 'helo'}
print(roll['harry'])
print(roll['ron'])
print(roll['hermione'])
1 2 helo
names = {1: 'harry', 2:'ron', 3:'hermione'}
print(names[1])
print(names[2])
print(names[3])
harry ron hermione
wtf = {1:'bla', 'ahem':2, 'food':'yes', 47:0}
print(wtf['ahem'])
print(wtf[47])
print(wtf['food'])
2 0 yes
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())
v1, v2, v3 = roll.values()
print(v1, v2, v3)
3 dict_keys(['harry', 'ron', 'hermione']) harry ron hermione dict_values([1, 2, 3]) 1 2 3
# Lists
l1 = [1, 2, 3, 4, 5]
for x in l1:
print(x)
1 2 3 4 5
list_1 = [1,2,3,4,5]
i = 0
while i < len(list_1):
print(list_1[i])
i += 1
1 2 3 4 5
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
l1 = [1, 2.0, 3, 4, 'abc']
for index, value in enumerate(l1):
print(index, value, type(index))#, type(value))
0 1 <class 'int'> 1 2.0 <class 'int'> 2 3 <class 'int'> 3 4 <class 'int'> 4 abc <class 'int'>
# Tuples
t1 = ('a1', 'a2', 'a3', 'a4')
for x in t1:
print(x)
a1 a2 a3 a4
# Dictionaries
d1 = {'key1': 'val1', 'key2':'val2', 'key3': 'val3'}
print(d1.items(), type(d1.items()))
for k, v in d1.items():
print(k, v)
dict_items([('key1', 'val1'), ('key2', 'val2'), ('key3', 'val3')]) <class 'dict_items'>
key1 val1
key2 val2
key3 val3
# Similar thing for lists
l1 = ['a1', 'a2', 'a3']
for idx, val in enumerate(l1):
print(idx, val)
0 a1 1 a2 2 a3
questions = ['name?', 'marks?', 'hobby?', 'something', 'nope']
answers = ['Student', "zero :'(", 'sleeeping ^_^', 10, 15]
for q, a in zip(questions, answers):
print(q, a)
name? Student marks? zero :'( hobby? sleeeping ^_^ something 10 nope 15
for i, (q, a) in enumerate(zip(questions, answers)):
print(i, q, a)
0 name? Student 1 marks? zero :'( 2 hobby? sleeeping ^_^ 3 something 10 4 nope 15
# List comprehensions
w_letters = []
for letter in 'aword':
w_letters.append(letter)
print(w_letters)
['a', 'w', 'o', 'r', 'd']
h_letters = [letter for letter in 'aword' ]
print( h_letters)
['a', 'w', 'o', 'r', 'd']
ss = [i for i in range(101) if i%2==0]
print(ss)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]
Exercise: Using list comprehension technique, store the squares of the numbers starting from 1 to 20 in a list
a= [i**2 for i in range(1,21)]
print(a)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
# General structure
# [expression for item in list if condition]
h_letters = [ letter for letter in 'aword' if letter != 'o']
print(h_letters)
['a', 'w', 'r', 'd']
[2*i for i in range(10) if i != 5]
[0, 2, 4, 6, 8, 12, 14, 16, 18]
# General Structure
# def functionName(argument1, argument2, argumentN):
# statement(s)
# return return1, return2, returnN
# You can also return nothing.
def addition_custom(n1, n2):
# add_res = n1 + n2
return n1+n2 #add_res #n1+n2
def list_of_my_functions():
functions = ['addition_custom(n1, n2)']
for i in functions:
print(i)
return functions
print(addition_custom(5, 10))
res = addition_custom(5, 10)
print(res)
list_of_my_functions()
15 15 addition_custom(n1, n2)
['addition_custom(n1, n2)']
def calculator(n1, n2):
sum_, substract, multiplication, division = n1 + n2, n1-n2, n1*n2, n1/n2
print('Sum: ', sum_)
print('substract: ', substract)
print('multiplication: ', multiplication)
print('division: ', division)
return 0;
x = calculator(4,2)
print(x)
Sum: 6 substract: 2 multiplication: 8 division: 2.0 0
Exercise: Write to program to make a calculator using function. Ask users to put the name of the operation that they want to perform. Next ask them to give the numbers for performing their chosen operations. Finall dispaly the result.
def even(n):
if n % 2 == 0:
is_even = True
else:
is_even = False
return is_even
def even(n):
is_even = n % 2 == 0
return is_even
n1 = 4
print(even(n1))
n2 = 7
print(even(n2))
True False
def even(n):
return n % 2 == 0
n1 = 20
print(even(n1))
n2 = 13
print(even(n2))
True False
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
def addC(n1, n2=4, n3=5):
return n1+n2+n3
print(addC(5, 3))
13
# Default Values
def power(x, p=1):
return x**p
print(power(x=10))
print(power(10, 3))
10 1000
# Default values MUST be filled from the right
def power(x=1, p):
return x**p
print(power(10, 3))
File "<ipython-input-95-fc05662a8312>", line 2 def power(x=1, p): ^ SyntaxError: non-default argument follows default argument
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())
6 0
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
f1 = open('afile', 'w')
f1.write('zzzz... huh?\n')
f1.write('*cough cough*')
f1.close()
f1 = open('afile', 'r')
c1 = f1.readline()
c2= f1.readline()
print(c1,c2)
f1.close()
zzzz... huh? *cough cough*
f1 = open('afile', 'r+')
f1.write('zzzz... huh?\n')
f1.write('*cough cough*')
c1 = f1.readline()
c2= f1.readline()
print(c1,c2)
f1.close()
zzzz... huh? *cough cough*
f1 = open('afile', 'r')
c1 = f1.read()
print(c1)
f1.close()
zzzz... huh? *cough cough*zzzz... huh? *cough cough*
f1 = open('afile', 'r')
for c1 in f1:
print(c1)
f1.close()
zzzz... huh? *cough cough*zzzz... huh? *cough cough*
s1 = 'abcd'
s2 = 'defg'
print(s1)
print(s2)
abcd defg
print(s1+s2)
abcddefg
print(s1.upper())
ABCD
print(len(s1))
4
s3 = ' this is a sentence '
print(s3, len(s3))
this is a sentence 32
s4 = s3.strip()
print(s4, len(s4))
this is a sentence 18
l1 = (s3.strip()).split() # other arguments for split
for i in l1:
print(i)
print(l1)
this is a sentence ['this', 'is', 'a', 'sentence']
s4 = ' '.join(l1)
print(s4)
this is a sentence
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?