In [1]:
print('Hello!')
Hello!
In [3]:
# This is a comment

'''
This is 
a 
multi-line 
comment
'''
Out[3]:
'\nThis is \na \nmulti-line \ncomment\n'


Basic Python data types:

1. Strings

2. Integers

3. Floats

4. Complex Numbers

5. Boolean

In [4]:
# 1. Strings:

print('This is a string')
print("This is a string too")
print('''This is a string three!''')

s = "\nThis is a str'ing"
print(s)
print(type(s))
This is a string
This is a string too
This is a string three!

This is a str'ing
<class 'str'>
In [5]:
# 2. Integers

i = 5
print(i)
print(type(i))
5
<class 'int'>
In [6]:
# 3. Floats

f = 4.3
print(f)
print(type(f))
4.3
<class 'float'>
In [7]:
# 4. Complex Numbers

c1 = 2 + 3j
c2 = complex(4,5)
print(c1)
print(c2)
print(type(c1), type(c2))

print('\n')
print(c1.real)
print(c1.imag)
(2+3j)
(4+5j)
<class 'complex'> <class 'complex'>


2.0
3.0
In [8]:
# 5. Boolean

b = True
c = False
print(b)
print(c)
print(type(b))
print(type(c))
True
False
<class 'bool'>
<class 'bool'>


Taking Input:

In [9]:
# raw_input() #Python2
ip = input('Enter an integer:')
print(type(ip))
Enter an integer:32
<class 'str'>

Type Conversion:

In [10]:
print(int(ip), type(int(ip)))
print(float(ip), type(float(ip)))

ip2 = int(input('Enter an integer:'))
print(ip2, type(ip2))
ip3 = float(input('Enter a number:'))
print(ip3, type(ip3))
32 <class 'int'>
32.0 <class 'float'>
Enter an integer:32
32 <class 'int'>
Enter a number:45.2
45.2 <class 'float'>
In [11]:
i = 10
print(i, type(i))
print(str(i), type(str(i)))

f = 0.5
print(f, type(f))
print(str(f), type(str(f)))
10 <class 'int'>
10 <class 'str'>
0.5 <class 'float'>
0.5 <class 'str'>
In [12]:
# Implicit type-conversions

b1 = True
b2 = False
print(b1 + b2 + b1 + b1)
3
In [13]:
print(bool(0))
print(bool(100))
print(bool(-100))
False
True
True
In [14]:
# Some ways to print
a = 5
b = 6

print('This',a,'is a',b)

print('This {} is a {}'.format(a , b))

print('This %d is a %d' %(a,b))
This 5 is a 6
This 5 is a 6
This 5 is a 6

Take as input an integer and a float. Print the integer and the float. Also print their sum along with the type of the sum.

In [15]:
i = int(input('Enter an integer:'))
f = float(input('Enter a float:'))

s = i + f

print(s, type(s))
Enter an integer:45
Enter a float:2.3
47.3 <class 'float'>


Quick Recap:

1. print, and comments

2. Basic Python data types (str, int, float, complex, bool)

3. Taking Inputs

4. Type Conversions



Python Operators:

1. Arithmetic Operators

2. Assignments Operators

3. Relational Operators

4. Logical Operators

5. Bitwise Operators

6. Membership Operators

7. Identity Operators

In [16]:
# 1. Arithmetic Operators

n1 = 10
n2 = 3

print('Add', n1 + n2)
print('Subtract',n1 - n2)
print('Multiply',n1 * n2)
print('Division',n1 / n2)
print('Remainder (Division)', n1 % n2)
print('Floor Division',n1 // n2)

print('\n')
print('Exponentiation',n1 ** 2)
print('Exponentiation',n1 ** 0.5)
print('Exponentiation',n1 ** -2)
Add 13
Subtract 7
Multiply 30
Division 3.3333333333333335
Remainder (Division) 1
Floor Division 3


Exponentiation 100
Exponentiation 3.1622776601683795
Exponentiation 0.01
In [17]:
# 2. Assignment Operators

n3 = 20
n4 = 6

n3, n4 = 20, 6
print(n3, n4)

n3 += n4 # Equivalent to n3 = n3 + n4
print(n3)
n3 -= n4 # Equivalent to n3 = n3 - n4
print(n3)
n3 *= n4 # Equivalent to n3 = n3 * n4
print(n3)
n3 /= n4 # Equivalent to n3 = n3 / n4
print(n3)
n3 %= n4 # Equivalent to n3 = n3 % n4
print(n3)

n3 = 20

n3 //= n4 # Equivalent to n3 = n3 // n4
print(n3)
n3 **= n4 # Equivalent to n3 = n3 ** n4
print(n3)
20 6
26
20
120
20.0
2.0
3
729
In [18]:
# 3. Relational Operators

n1 = 10
n2 = 5

print(n1 == n2)
print(n1 != n2)
print(n1 > n2)
print(n1 < n2)
print(n1 >= n2)
print(n1 <= n2)
False
True
True
False
True
False

Take four numbers as input. Display whether the sum of the first two numbers is greater than or equal to the sum of the latter two numbers

In [19]:
# 4. Logical Operators

b1 = True
b2 = False

print(not b1)
print(b1 and b2)
print(b1 or b2)

print(0 and 1)
print(0 or 1)
False
False
True
0
1
In [20]:
# 5. Bitwise Operators

i1 = 15 # 1111
i2 = 6 #  0110

print(i1 & i2) # and
print(i1 | i2) # or
print(i1 ^ i2) # xor
print(~i1) # one's complement
print(i1 << 2) # left shift
print(i1 >> 2) # right shift
6
15
9
-16
60
3
In [21]:
# 6. Membership Operators

print('str' in 'string')
print('ni' not in 'convenient')
True
False
In [22]:
# 7. Identity Operators

string1 = 'abcd'
string2 = 'efgh'
print(string1 is string2)
False


Quick Recap:

1. print, and comments

2. Basic Python data types (str, int, float, complex, bool)

3. Taking Inputs

4. Type Conversions

5. Python Operators (arithmetic, assignment, relational, logical, bitwise, membership, identity)



Conditional Statements: if-elif-else

In [22]:
# General structure

# if condition1:
#     statement(s)

# elif condition2:
#     statement(s)

# elif condition3:
#     statement(s)

# ...

# elif conditionN:
#     statement(s)

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

if a1 > a2:
    print('a1 is greater')
elif a1 < a2:
    print('a2 is greater')
elif False:
    print('This statement will never be reached')
else:
    print('a1 and a2 are equal')
a2 is greater

WAP that takes an integer as input, and prints whether the number is odd or even.

In [24]:
x = int(input('Input an integer:'))
if x%2:
    print(x,'is odd')
else:
    print(x, 'is eve')
Input an integer:45
45 is odd


Python Indentations

1. There are no braces {} in Python to demarcate blocks of code.

2. Indentations (whitespaces) demarcate blocks of code.

3. Changes in indentation mark where a block begins, and where it ends.

4. A common convention: 4 spaces (or 1 tab, which the editor converts to 4 spaces).

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

if a1 == 10:
    if a2 == 20:
        if a3 == 30:
            print('a1 == 10, a2 == 20, a3 == 30')
        else:
            print('a1 == 10, a2 == 20, a3 != 30')
    else:
        print('a1 == 10, a2 != 20, a3 != 30')
else:
    print('a1 != 10, a2 != 20, a3 != 30')
a1 == 10, a2 == 20, a3 == 30


Loops!

In [25]:
# 1. for loops

# General Structure

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

for i in range(6): # [0, 1, 2, 3, 4, 5]
    print(i)
print('')
for i in 'abc':
    print(i)
0
1
2
3
4
5

a
b
c
In [27]:
# range with 2 arguments:
# range(start, end)

for i in range(0,5+1):
    print(i)

print('')
for i in range(5,10):
    print(i)
0
1
2
3
4
5

5
6
7
8
9
In [28]:
# range with 3 arguments
# range(start, end, steps)

for i in range(0,20,2):
    print(i)
0
2
4
6
8
10
12
14
16
18
In [29]:
# Loop in the opposite step direction

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

str1 = 'abcdefg'

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

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 [32]:
# 2. while loops

# General Structure

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

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

break, continue

In [34]:
# break: break out of the inner-most loop (not the if-else block!)

i = 0
while 1:
    i += 1
    if i > 10:
        break
print(i)
11
In [35]:
# continue: go to the start of the inner-most loop (not if-else blocks)

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


Recap:

1. print, and comments

2. Basic Python data types (str, int, float, complex, bool)

3. Taking Inputs

4. Type Conversions

5. Python Operators (arithmetic, assignment, relational, logical, bitwise, membership, identity)

6. if-elif-else

7. Python Indentations

8. Loops (for, while)

9. break, continue, pass



Functions

In [36]:
# General Structure

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

# You can also return nothing.
In [37]:
# functions can accept arguments, and can return values

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 [38]:
def even(n):
    return n % 2 == 0

n1 = 20
print(even(n1))
n2 = 13
print(even(n2))
True
False
In [39]:
# functions can return multiple values

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 [40]:
# You can provide default values to the parameters of a function

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

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

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

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


Recap:

1. print, and comments

2. Basic Python data types (str, int, float, complex, bool)

3. Taking Inputs

4. Type Conversions

5. Python Operators (arithmetic, assignment, relational, logical, bitwise, membership, identity)

6. if-elif-else

7. Python Indentations

8. Loops (for, while)

9. break, continue, pass

10. Function



Classes

In [42]:
# General Structure

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

# className objectName
# objectName.function1()

# # public members
# def functionName():
#     statement(s)
# # private members
# def __name__():
#     statements(s)

# Constructor:
# def __init__():
#     statements(s)

Principles of Object Oriented Programming

1. Abstraction

2. Encapsulation

3. Inheritance

4. Polymorphism

In [43]:
class rectangle:
    
    def __init__(selfabc, length=0, width=0):
        selfabc.length = length
        selfabc.width = width
    
    def area(self123):
        return self123.length * self123.width
In [44]:
var_rect = rectangle(length=2, width=3)
print(var_rect.area())
var_rect = rectangle()
print(var_rect.area())
6
0
In [45]:
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


Data Structures: Lists, Tuples, Sets and Dictionaries

1. List: Mutable array that can store any object

In [46]:
# lists store data of any type

l1 = [2, 3.5, 'apple', False]
print(l1)
print(l1[0])
print(l1[2])
[2, 3.5, 'apple', False]
2
apple
In [47]:
# can create empty lists, can append elements to a list

l1 = []
print(l1)
l1.append('Five')
print(l1)
[]
['Five']
In [48]:
# '+' for lists defined as concatenation

l1 = ['abc', 'def']
l2 = ['abc2', 'def2']
print(l1 + l2)
l3 = [4,5]
l4 = [6,7]
print(l3 + l4)
['abc', 'def', 'abc2', 'def2']
[4, 5, 6, 7]
In [49]:
# can append lists to lists

l1 = ['abc', 'def']
l2 = [l1, 'Six']
print(l2)
[['abc', 'def'], 'Six']
In [50]:
# remove the first occurance of an element

l1 = [2, 3.5, 'apple', False, 'apple']
l1.remove('apple')
print(l1)
[2, 3.5, False, 'apple']
In [51]:
# insert element in a specific position

l1 = [2, 3.5, False, 'apple']
l1.insert(2, 'apple')
print(l1)
[2, 3.5, 'apple', False, 'apple']
In [52]:
# delete last element

l1 = [2, 3.5, 'apple', False, 'Five']
x = l1.pop()
print(x)
print(l1)
Five
[2, 3.5, 'apple', False]
In [53]:
# all possible operations on a list

print(dir(l1))
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
In [54]:
l1 = [2, 3.5, 'apple', False, 'Five']
print(len(l1))
5
In [55]:
l1 = [2, 3.5, 'apple', False, 'Five']
print(l1.index('apple'))
2
In [56]:
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 [57]:
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 [58]:
l1 = [1, 2, 3, 4]
l2 = l1
l2.append(5)
print(l2)
print(l1)

print('\n')
l3 = list(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]

2. Tuples: Immutable arrays that can store any object

In [59]:
t1 = (2, 3, 'banana')
print(t1)

# access a particular element

print(t1[0])
(2, 3, 'banana')
2
In [60]:
# create empty tuples

t2 = ()
print(t2)
()
In [61]:
# cannot modify tuples

t1[0] = 1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-61-4035f236510d> in <module>()
      1 # cannot modify tuples
      2 
----> 3 t1[0] = 1

TypeError: 'tuple' object does not support item assignment

3. Set: No duplicates

In [62]:
s1 = set({1, 2, 2, 3, 4})
print(s1)
{1, 2, 3, 4}
In [63]:
s1 = set({1, 2, 2, 3, 'abc', 4.5, 2.0})
print(s1)
{1, 2, 3, 4.5, 'abc'}
In [64]:
# Sets are useful in getting only the unique elements

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]

4. Dictionaries: Map keys to values

In [65]:
# key:value - maps key to value

roll = {'harry':1, 'ron':2, 'hermione':3, 'hermione':'top student'}

print(roll['harry'])
print(roll['ron'])
print(roll['hermione'])
1
2
top student
In [66]:
# both kets and values can be of any data type

names = {1: 'harry', 2:'ron', 'hermione':3}

print(names[1])
print(names[2])
print(names['hermione'])
harry
ron
3
In [67]:
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])

Iterate over data structures

In [68]:
# Iterate over Lists

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

for x in l1:
    print(x)
1
2
3
4
5
In [69]:
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 [70]:
l1 = [1, 2, 3, 'cat', 5]

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

t1 = ('a1', 'a2', 'a3', 'a4')
for x in t1:
    print(x)
a1
a2
a3
a4
In [72]:
# 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 [73]:
# Similar way of iterating for lists

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

for idx, val in enumerate(l1):
    print(idx, val)
0 a1
1 a2
2 a3
In [74]:
l1 = [1, 2, 3, 4, 5]
l2 = ['a', 'b', 'c', 'd', 'e']

for q, a in zip(l1, l2):
    print(q, a)
    
print('')
    
for i, (q, a) in enumerate(zip(l1, l2)):
    print(i, q, a)
1 a
2 b
3 c
4 d
5 e

0 1 a
1 2 b
2 3 c
3 4 d
4 5 e
In [75]:
# List comprehensions

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

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


Recap:

1. print, and comments

2. Basic Python data types (str, int, float, complex, bool)

3. Taking Inputs

4. Type Conversions

5. Python Operators (arithmetic, assignment, relational, logical, bitwise, membership, identity)

6. if-elif-else

7. Python Indentations

8. Loops (for, while)

9. break, continue, pass

10. Function

11. Data Structures (lists, tuples, sets, dictionaries)



File I/O

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

f1.write('Line 1\n')
f1.write('Line 2\n')

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

c1 = f1.readline()
print(c1)

f1.close()
Line 1

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

c1 = f1.read()
print(c1)

f1.close()
Line 1
Line 2

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

for c1 in f1:
    print(c1)

f1.close()
Line 1

Line 2



String functions

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

Regular expressions

In [85]:
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??

Python Libraries -

1. Linear Algebra Routines (Numpy)

2. Scientific Computation (Scipy)

3. Plots (Matplotlib)

4. Machine Learning (scikit-learn)

5. Data Handling (pandas)

6. Algebraic Evaluations (SymPy)

7. Natural Language Processing (nltk)

8. Web Scraping (BeautifulSoup)

9. Computer Vision: OpenCV Python APIs



References:


  1. The Python Documetation Tutorial https://docs.python.org/3/tutorial/index.html