Python

Basic Functions


In [2]:
abs(-3) # Gives the absolute value of a variable


Out[2]:
3

In [3]:
all([1,2,3,0]) # Returns True if all iterators are true.


Out[3]:
False

In [4]:
any([1,2,3,4,0]) # If any value is true among the iterators


Out[4]:
True

In [24]:
def prime(): 
    pass
print(callable(prime))

# Returns True if object has a return statement
# instances of classes are callable if they have __call))() method
a = 3
callable(a)


True
Out[24]:
False

In [27]:
chr(49) # Returns the ASCII represenattion of the number


Out[27]:
'1'

In [30]:
complex('3')


Out[30]:
(3+0j)

In [ ]:
dir() # Returns a list of names in the current lcoal scope

In [ ]:
import numpy as np
dir(numpy)

In [42]:
divmod(10,3) # Returns the quotient and the remainder


Out[42]:
(3, 1)

In [47]:
temp = ['a', 'b', 'f']
list(enumerate(temp, start = 6))


Out[47]:
[(6, 'a'), (7, 'b'), (8, 'f')]

In [50]:
# Why we use enumerate because it let's use use both the index and the value of the sequence
for index, value in enumerate(temp):
    print('The index is %d amd the letter is %c'%(index, value))


The index is 0 amd the letter is a
The index is 1 amd the letter is b
The index is 2 amd the letter is f

In [51]:
format(45, 'b') # To convert in different integer representations


Out[51]:
'101101'

In [ ]:
globals() # returns a dictionary of current global symbol table
# You can use to see the globals of a function or class

In [60]:
a = 3
id(a) # Kind of address in the memory


Out[60]:
94112596728384

In [62]:
input('Give me something as input')


Out[62]:
'Kushaj'

In [ ]:
locals() # returns the free variables

In [64]:
a = 2.3412456432
round(a, 3)


Out[64]:
2.341

Build In Constants

  • False
  • True
  • None -> Represents absence of a value
  • NotImplememted -> Returned by some functions when the arithmeatic operation is not implemeted like \__add\__

Comparison


In [70]:
if(3 or 0):
    print('Or is True')
if(3 and 0):
    print('And is True')


Or is True

In [72]:
if 3 is 3:
    print('The world is round')

if 3 is not 4:
    print('The world is round')


The world is round
The world is round

In [78]:
a = 3
b = 3.0
if (a == b):
    print('Double = works')

if (a is b):    # Is does the strict comparison
    print('Is works')


Double = works

In [79]:
# Bitwise operations
x | y # THe or operation
x ^ y # The xor operation
x & y # And operation
x << y # Multiplyting by 2**y
~x # The bits of x reversed


Out[79]:
-4

In [ ]:
# Some sequence operations
s.count(x)   # Return the total number of occurences of x
s.index(x[, i[, j]]) # First occurence of x at or after i and before index j
x in s
x not in s
s+t # Concatenation of two sequences

Lists


In [85]:
a = list(('a','b','c','d'))
print(a)


['a', 'b', 'c', 'd']

In [88]:
a = ['a','b','c','d']
print(a)


['a', 'b', 'c', 'd']

In [96]:
myList = [4,5,8,1,23,4,6,8]
myList.sort(reverse = False)
print(myList)


[1, 4, 4, 5, 6, 8, 8, 23]

In [97]:
myList.append('a')
print(myList)


[1, 4, 4, 5, 6, 8, 8, 23, 'a']

In [98]:
myList.remove(1)
print(myList)


[4, 4, 5, 6, 8, 8, 23, 'a']

In [99]:
a = myList.pop()
print(a)


a

In [100]:
myList.insert(3, 'b')
print(myList)


[4, 4, 5, 'b', 6, 8, 8, 23]

Tuples

Immutable sequences to store hetrogenous data


In [103]:
myTuple = tuple((1,2,3,'a'))
print(myTuple)


(1, 2, 3, 'a')

In [112]:
myTuple = (1,2,3,'a', 1+2j)
print(myTuple[3])
# you cannot now add or remove elements from a tuple after its creation


a

Sets

Unordered collection of elements and thus they do not support indexing, slicing.
Their are two types of sets nameley

  1. Sets -> They are mutable amd thus is not hashable. Can use operations like add() or remove().
  2. Frozenset -> Immutable and hashable and thus it can be used as a dictionary key.

In [133]:
mySet = set((1,2,3,4,'a'))
print(mySet)


{1, 2, 3, 4, 'a'}

In [134]:
mySet[1]


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-134-3f1dd0987896> in <module>()
----> 1 mySet[1]

TypeError: 'set' object does not support indexing

In [135]:
mySet.remove(1)

In [136]:
mySet = {1,2,3,'a',1+2j}
print(mySet)


{1, 2, 3, (1+2j), 'a'}

In [137]:
len(mySet)


Out[137]:
5

In [138]:
2 in mySet


Out[138]:
True

In [139]:
mySet2 = {'a','b','c','d'}
mySet.isdisjoint(mySet2)   # Tells whether two sets have all differen elements


Out[139]:
False

In [140]:
mySet3 = {1,2}
mySet3.issubset(mySet)


Out[140]:
True

In [141]:
mySet.union(mySet2)


Out[141]:
{(1+2j), 1, 2, 3, 'a', 'b', 'c', 'd'}

In [142]:
myFrozenSet = frozenset((1,2,3,4))
myFrozenSet


Out[142]:
frozenset({1, 2, 3, 4})

Dictionary

Objects that are not hashable like lists, tuples, sets cannot become keys of a dict.


In [145]:
myDict = dict(one=1, two=2, three=3, four=4)
myDict


Out[145]:
{'four': 4, 'one': 1, 'three': 3, 'two': 2}

In [146]:
len(myDict)


Out[146]:
4

In [148]:
myDict['one']


Out[148]:
1

In [153]:
# You can use __missing__ to specify what to do when a key is not found
class Counter(dict):
    def __missing__(self, key):
        print('The key is not present')
        return 0
myDict = Counter()
print(myDict['red'])


The key is not present
0

In [154]:
myDict = {'one':1, 'two':2, 'three':3}
myDict


Out[154]:
{'one': 1, 'three': 3, 'two': 2}

In [156]:
# You can check for keys
'one' in myDict


Out[156]:
True

In [164]:
# If you want to iterate over the keys in a dictionary
for key in iter(myDict):
    print(key)


one
two
three

In [165]:
myDict.get('one')


Out[165]:
1

In [167]:
print(myDict.get('zero'))


None

In [169]:
for values in myDict.items():
    print(values)


('one', 1)
('two', 2)
('three', 3)

In [171]:
# Best way to iterate over a dictionary
for key, value in myDict.items():
    print('For key = ', key, ' the value is ', value)


For key =  one  the value is  1
For key =  two  the value is  2
For key =  three  the value is  3

In [179]:
myDict.update({'zero':0})
myDict


Out[179]:
{'one': 1, 'three': 3, 'two': 2, 'zero': 0}

Exceptions

All exceptions are instances of a class that derieves from BaseExceptions.
General approach to handle exceptions

try:
    ...
except SomeExceptionName:
    What you want to do if you face that exception
Various base classes

  • BaseException -> Base class for all built in exceptions. It is not directly inherited by user-defined exceptions.
  • Exception -> All built-in, user-defined exceptions are derived form this class
  • ArithmeticError -> Base Class for those exceptions that are raised during arithematic operations like OverflowError, ZeroDivisionError, FloatinPointError.
  • BufferError
  • LookupError -> When a key or index used on a mapping or sequence is invalid like IndexError, KeyError

In [191]:
for _ in range(2):
    try:
        x = int(input('Enter a anumber '))
    except ValueError:
        print('You did not enter a number')
    finally:
        print('This line will always be executed')


This line will always be executed
You did not enter a number
This line will always be executed

In [203]:
# To create new exceptions
class B(Exception):
    pass

In [206]:
try:
    pass
except B:
    pass

In [208]:
a = 3
assert (a == 4)
# We would get an exception as a is 3 not 4


---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-208-6ad9d198ab8b> in <module>()
      1 a = 3
----> 2 assert (a == 4)

AssertionError: 

Various exception that youmay face

  • __AssertionError__ -> When an assert statement fails
  • __AttributeError__ -> When an assignment or attribute reference fails
  • __EOFError__ -> Most proabl;y when you miss a bracket.
  • __FloatingPointError__ -> When a flaoting point operation fails
  • __ImportError__
  • __ModuleNotFoundError__
  • __IndexError__ -> During incorrect indexing of a sequence
  • __KeyError__ -> When a mapping dictionary key is not found in set of existing keys
  • __KeyboardInterrupt__
  • __MemoryError__ -> When an operation runs out of memory but it can be overcome by deleting some objects
  • __NameError__ -> When a local or global name is not found
  • __OSError__ -> When a system related error occurs like failed file I/O operation or disk full.
  • __OverflowError__ -> When result of arithematic operation is too large to be represented.
  • __RecursionError__ -> When maximum recursion depth is exceeded.
  • __ReferenceError__ -> When we try to access an attribute of the referent after it has been garbage collected.

In [212]:
import sys
sys.getrecursionlimit()
# Always remember that tail recursion is not efficient inpython so 
# always try to solve the problem iteratively that recursively in pyton.


Out[212]:
3000

Fucntional Programming

It is a process of building software by composing pure functions, avoiding shared state, muatble data and side effects. COntrast with object oriented programming hwere application state is usually shared and colocated with methods in objects.

itertools -- Functions for creating iterations for efficient looping


In [223]:
import itertools
import operator
data = [3,4,6,1,9,0,7,5,8]
print(data)


[3, 4, 6, 1, 9, 0, 7, 5, 8]

In [221]:
# Accumulate -> To make a iterator that returns accumulated sums
list(itertools.accumulate(data, func=operator.add))


Out[221]:
[3, 7, 13, 14, 23, 23, 30, 35, 43]

In [225]:
# Chain -> Make an iterator that returns elements from first iterable until it is exhausted.
list1 = [1,2,3,'a']
list2 = ['b', 'c', 'd']
list(itertools.chain(list1, list2))


Out[225]:
[1, 2, 3, 'a', 'b', 'c', 'd']

In [ ]:
# Combinations -> Returns subsequences of length r from input iterables
list(itertools.combinations(data,3))

In [ ]:
# Combinations with replacements
list(itertools.combinations_with_replacement(data, 3))

In [ ]:
# cycle -> To cycle through the sequence. Note it is infinte

These were some of the iterators. I did not get into the glory details of the topic as data science does not require them. And any other functions that I did not dicuss are because they are not used in data science and deep learning.