You are on page 1of 128

# python - if you want programmers in easy,

learn python
# Start from 0 Level
# REPL - A read–eval–print loop
# It is one of the fastest growing language
# it is used everywhere like machine learning,
GUI, s/w development, Web development
# Thatswhy it is called general purpose
language
# what is python - it is a pgrmng language
# interpreter, object oriented , Highlevel
# What is compiler - It is translator,
Translate the whole prg and execute
# What is Interpreter - Line by line translate
and execute
# It supports oops
concept(Inheritance,polymorphism)
# Procedural language(If,elif,while,for),
# Functional programming(Mathematical)
# is it new language
# Created By Guido van Rossum in late 1980's,
but java 1995
# Python from ABC
# It is not snake name from Monty python
flying circus
# after booming machine learning, AI,
scientiest using this language for easy
purpose
# famous companies using python like google
# python 1.0 - 1994
# python 2.0 - 2000
# pyhton 3.0 - 2008
# versions different working

# python installation
# install interpreter - python 3.7
# IDE (Mention syntax error)- Pycharm IDE
# Interactive mode and Scripting mode
# Interactive mode
'''a=10
b=20
c=a+b
print(c)''' # on the spot output
# Scripting mode
# First save the program then execute when
ever need

# Session3 - Using IDLE


# You instruct computer do - like email, msg
# computer understand 0's and 1's
# but you speak with prg languages
'''4 + 2
4 - 3
3 * 4
_ + 4 # _ mention output of the previous
operation
5 / 2 # received float answer
5 // 2 # int divison or floor divison
2 * 2 * 2
2 ** 3
"hi" + "python"
"python" * 3
print("navin")
print('navin's laptop')
print("navin's laptop")
print('navin\'s laptop')
print("c:\docs\navin") # \n - new line
print(r"c:\docs\navin") # raw string - print as
it is '''

# Values - Like a letter or number


'''a=10 # value of a is 10
x="Hello" # value of x is Hello'''
# Variables - it is container of the value
# A name that refers to the value, assignment
operation
# reassign the value in variable it's possible
'''a=2 # given name for memory for ex:
a assign for 1045
b=3 # Ex: address for the home
print(id(a)) # Heap memory
print(type(a)) # data-type of variable
sum=a+b # Like a brain memory
print(sum)
a=5 # reassign
sum=a+b #Here a,b and sum are variables
print(sum)
a= 10
b= a
print(id(a))
print(id(10))
print(id(b))
k = 10
print(id(k))
# same heap memory, so python is more memory
efficient
a=9
print(id(a))
print(id(b))
k=a
print(id(k))
b=8
print(id(b))
print(id(10)) # now no one refer 10, garbage
collector handled
'''

'''>>> name = "scion" # string operation in


variable
>>> name
'scion'
>>> name[0]
's'
>>> name[3]
'o'
>>> name[-1]
'n'
>>> name[-4]
'c'
>>> name[0:4]
'scio'
>>> name[1:10]
'cion'
>>> name[0:3] = "r and d" #
string immutable in python
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
name[0:3] = "r and d"
TypeError: 'str' object does not support item
assignment
>>> name[3] = "s"
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
name[3] = "s"
TypeError: 'str' object does not support item
assignment
>>> "my" + name[2:]
'myion'
>>> myoffice = "scion"
>>> len(myoffice)
5 '''

# Local variable and Global variables


'''a=10 # Global
def abc():
b=20 # Local
print(a)
print(b)
abc()
def abc1():
c=40
print(a)
print(c)
abc1()'''

'''def abc():
b=20 # Local
print(b) ''' # Error b does not defined

'''def abc():
a=20 # Local
print(a)
def xyz():
a=30 # Local
print(a)
abc()
xyz()'''

'''a=25
def abc():
#a=20 # Local
#a="scion"
#b=30
#a=a+b # local variable 'a'
referenced before assignment
print(a)
abc()'''

# Naming rules
# a-z, A-Z
# a123, _a, a_1 (Posssible)
# 1a, a 1 (not possible)
# Case sensitive
# unable to reserved words(Keywords)
# Resonable length

#Keywords - It is used by the compiler to


parse a program
# such as import,and,as,del,if,elif,in,try...

# Refresh value, Variable, Keyword


# datatypes- it is a type of data, process
with in the prg
'''>>> # Data Types
>>> # None
>>> # Numeric(int, float, complex, bool)
>>> # Sequence(list, tuple, set, string, range)
>>> # Dictionary

>>> # None - explaination


>>> # all languages using null values, python
using None
>>> # def sum(self,a=None,b=None,c=None):

>>> # Numeric - float


>>> num = 2.5
>>> type(num)
<class 'float'>

>>> # Numeric - int


>>> num = 5
>>> type(num)
<class 'int'>
>>> # Numeric - complex
>>> num = 5 + 6j
>>> type(num)
<class 'complex'>
>>> a = 5.6
>>> b = int(a)
>>> type(b)
<class 'int'>
>>> b
5
>>> k = float(b)
>>> k
5.0
>>> c = complex(b,k)
>>> c
(5+5j)
>>> type(c)
<class 'complex'>

>>> # Numeric - bool


>>> b < k
False
>>> bool = b>=k
>>> bool
True
>>> type(bool)
<class 'bool'>
>>> # using diff operators
>>> int(True)
1
>>> int(False)
0

>>> # Sequence - List


>>> list = [34,45,67,78]
>>> type(list)
<class 'list'>

>>> # Sequence - set


>>> s = {23,45,56,56,78} # it has unique value
>>> s
{56, 45, 78, 23}
>>> type(s)
<class 'set'>

>>> # Sequence - tuple


>>> t = (25,45,67,78)
>>> type(t)
<class 'tuple'>

>>> # Sequence - string


>>> str = "scion"
>>> str = 'scion'
>>> type(str)
<class 'str'>
>>> # python dont have char type

>>> # Sequnce - range


>>> range(10) # start=0, stop = 10, step = 1
range(0, 10)
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(2,10,2))
[2, 4, 6, 8]

>>> #Mapping - Dictionary


>>> # every value assign with key (Like
register number)
>>> # but list access from index value
>>> # key should be unique
>>> # {} using does not having repeat value
>>> d = { "10" : "ravi", "11":"rahul",
"12":"kavi"}
>>> d
{'10': 'ravi', '11': 'rahul', '12': 'kavi'}
>>> d.keys()
dict_keys(['10', '11', '12'])
>>> d.values()
dict_values(['ravi', 'rahul', 'kavi'])
>>> d["10"]
'ravi'
>>> d.get(10)
>>> d.get("10")
'ravi'
'''

# Operators

# Arithmetic Operators
#a=10
#b=4
'''c=a+b
c=a-b
c=a*b
#c=a/b
#c=a//b
#c=a%b
#c=a**b
print(c)'''

# Comparison Operators
'''a=10
b=4
#c=a<b
#c=a>b
#c=a<=b
#c=a>=b
#c=a!=b
#c=(a==b)
print(c)'''

# Logical Operators
'''a=10
b=9
c=8
d=12
f= a>b and c<d
#f= a<b or c>d
#f= not a>b
print(f)'''

# Assignment Operators
'''a=8
c=7
b=c # Assignment operator
#b+=a # Compound Assignment operator
(b=b+a)
#b-=a
b*=a
print(b)
a,b= 4,5 # Assign two values for two
variables
'''

# Bitwise Operators
'''a=5 # 0101
b=3 # 0011
#c=a&b # 0001
#c=a|b # 0111
#c=a^b # 0110
#c=~a # 1010
#c=a>>1 # 0010
#c=a<<1 # 1010
print(c)'''

# Membership Operators (Appear or not)


'''a=[2,3,4]
b="scion"
print(2 in a)
print(5 in a)
print(3 not in a)
print("c" in b)
print("e" in b)
print("o" not in b)'''

# Identity Operators (matching same value)


'''a=5
b=8
c="scion"
d="SCION"
print(a is b)
print(a is not b)
print(c is d)
print(c is not d)'''

#Operator Precedence (PEMDAS)


# parentheses
# Exponentiation
# Multiplication
# Division
# Addition
# Subtraction

'''print(5+4*3)
print((5+4)*3)
print(5**2*3+4)'''

# Number system
# Binary(0-1) # BIT
# Octal (0-7)
# Decimal(0-9)
# HexaDecimal (0-9,a-f)
'''>>> bin(36)
'0b100100'
>>> oct(36)
'0o44'
>>> hex(36)
'0x24'
>>> 0b110011
51
>>> 0o334
220
>>> 0x345
837
>>> oct(0b100100)
'0o44'
>>> hex(0o44)
'0x24'
'''

'''# Swap 2 numbers using variables


a = 5
b = 6
# step 1
#a=b
#b=a

# step 2
#temp = a
#a = b
#b = temp

# step 3
#a = a + b # 11 - using 4 bits all other 3
bits
#b = a - b # 11-6=5
#a = a - b # 11-5=6

# step 4
#a = a^b # a = 101, b = 110, a = 011
#b = a^b # a = 011, b = 110, b = 101 = 5
#a = a^b # a = 011, b = 101, a = 110 = 6

# step 5 (only python)


#a,b=b,a

print(a)
print(b)'''

# Math functions
'''>>> math.sqrt(25)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
math.sqrt(25)
NameError: name 'math' is not defined
>>> import math
>>> math.sqrt(25)
5.0
>>> math.pow(3,2) # 3 ** 2
9.0
>>> math.floor(2.9)
2
>>> math.ceil(2.1)
3
>>> math.pi
3.141592653589793
>>> import math as m
>>> math.sqrt(36)
6.0
>>> m.sqrt(36)
6.0
>>> from math import sqrt,pow
>>> sqrt(49)
7.0
>>> pow(4,5)
1024.0
'''

'''# User input in python


# step 1
x = input(" ") # usually
input get as string
y = input(" ")
z = x + y
print(z)

# step 2
x = input(" Enter the 1st Number ") # usually
input get as string so convert int or float
y = input(" Enter the 2nd Number ")
z = x + y
print(z)

# step 3
x = input(" Enter the 1st Number ")
a = int(x) # Convert
string to integer
y = input(" Enter the 2nd Number ")
b = int(y)
z = a + b
print(z)

# step 4 - No need to waste of code


x = int(input(" Enter the 1st Number "))
y = int(input(" Enter the 2nd Number "))
z = x + y
print(z)

# step 5 - Character
ch = input(" Enter a char ")
print(ch)

# step 6
ch = input(" Enter a char ")
print(ch[0])

# step 7
ch = input(" Enter a char ")[0]
print(ch)
'''

# Conditional or branching stmt


# check the condition in process
# Boolean condition Stmt
'''a=10
b=13
print(a<b)'''

# If condition stmt

'''age=int(input("Enter your age : "))


if(age>=18):
print("You are eligible for Voting")''' #
intendtation identify the block

# Alternative or Ifelse stmt


'''age=int(input("Enter your age : "))
if(age>=18):
print("You are eligible for Voting")
else:
print("You are not eligible for Voting")'''

# Chained Conditional or Elif stmt


'''mark = int(input("Enter the mark : "))
if(mark>=90):
print("S Grade")
elif(mark>=80):
print("A Grade")
elif(mark>=70):
print("B Grade")
elif(mark>=60):
print("C Grade")
elif(mark>=50):
print("D Grade")
else:
print("Fail")'''

'''# Nested if
mark = int(input("Enter the mark : "))
if(mark>=50):
if(mark>=90):
if(mark>95):
print("S+ Grade")
else:
print("S Grade")
else:
print("You are pass")
else:
print("You are fail")

'''
# Looping or iteration statement
# Statement continous running upto condition
satisfy
# for Loop
'''print("Hi welcome to python")
print("Hi welcome to python")
print("Hi welcome to python")
print("Hi welcome to python")
print("Hi welcome to python")'''

# range(start,stop=None,step=1)
# start=0 and step=1 default (any changes
mention value)
# Compulsory mention stop value
#for a in range(0,5,1):
'''for a in range(5):
print("Hi welcome to python")'''

'''print("Hi welcome 1")


print("Hi welcome 2")
print("Hi welcome 3")
print("Hi welcome 4")
print("Hi welcome 5")'''
'''for a in range(1,6): # or (0,5)
print("Hi welcome ",a)''' # print("Hi
welcome ",a+1)

# sum of values
'''s=0
s=s+1
s=s+2
s=s+3
s=s+4
s=s+5
s=s+6
s=s+7
s=s+8
s=s+9
s=s+10
print(s)'''

'''s=0
for a in range(1,11):
s=s+a
#print(s) # in the Loop
print(s) # Out the Loop'''
# for loop for list using range
'''l=[1,2,3,4,5]
s=0
for i in range(len(l)):
s=s+l[i] # accessing index value
l[0] to l[4]
print(s)'''

# for loop for list using without range


'''l=[1,2,3,4,5]
s=0
for i in l: # i denoting the first
value list not index value
s=s+i
print(s)'''

# while Loop
'''i=0 #
Initialization or start
while(i<5): # Condition
check or stop
print("Welcome to python")
i=i+1 # Iteration
or step size'''

'''i=0 # or i=1
while(i<5): # or i<=5
print("Welcome to python", i+1) # or i
i=i+1'''

'''i=1
s=0
while(i<=5):
s=s+i
i=i+1
print(s)'''

# for automaticaly take initial value and step


size but while loop must mention
'''l=[1,2,3,4]
i=0
s=0
while(i<len(l)): # Must mention len
s=s+l[i]
i=i+1
print(s)'''
# Break - break the loop come out from the
loop
'''for i in range(5):
if(i==3):
break
print(i)
print("We are out of the Loop")'''

# Continue - Leave the condition satisfy value


(or) skip the value
'''for i in range(5):
if(i==3):
continue
print(i)
print("We are out of the Loop")'''

# Pass - None or Nothing will happen


'''for i in range(5):
if(i==3):
pass
print(i)
print("We are out of the Loop")'''

'''str = "python"
for i in str:
if i=='h':
#break
#continue
pass
print(i)
print("Out from the loop")'''

# printing patterns

'''# step 1
print("# # # #")

# step 2
print("#")
print("#")
print("#")
print("#")
# step 3
print("#", end=" ")
print("#", end=" ")
print("#", end=" ")
print("#", end=" ")

# step 4
for j in range(4):
print("#", end=" ")
'''

'''# step 5
for i in range(4):
for j in range(4):
print("#", end=" ")
print()'''

'''# step 6
for i in range(4):
for j in range(i):
print("#", end=" ")
print()'''
'''# step 7
for i in range(4):
for j in range(i+1):
print("#", end=" ")
print()
'''

'''# step 8
for i in range(4):
for j in range(4-i):
print("#", end=" ")
print()'''

# for - else

'''num = [23,43,67,55,78]
for a in num:
if a % 5 == 0:
print(a)
break
else:
print("No one") # here else for if'''
'''num = [25,45,67,56,78]
for a in num:
if a % 5 == 0:
print(a) # without break
else:
print("No one") # here else for for
'''

'''num = [25,45,67,56,78]
for a in num:
if a % 5 == 0:
print(a)
break
else:
print("No one") # here else for for'''

# Prime number

'''num = int(input("Enter the number"))


for i in range(2, num):
if num % i == 0:
print(" Not Prime number ")
break
else:
print(" Prime ")'''

# Array in python

'''from array import *


arr = array('i', [5,3,6,8,4]) # where i is
TypeCode ex: I,u,b,B,h,H
# step 1
print(arr)
# step 2
print(arr.buffer_info()) # (memory space,
no.of elements)
# step 3
arr.reverse()
# step 4
print(arr[2])

# step 5
for a in range(len(arr)): # for a in
range(5)
print(arr[a])
# step 6
for a in arr: # for a in range(5)
print(a)
# step 7
arr1 = array(arr.typecode, (a*a for a in arr))
for a in arr1:
print(a)

# step 8
strarr = array('u', ['a', 'e', 'i'])
#print(strarr)

# step 9
#print(strarr.buffer_info()) # (memory
space, no.of elements)

# step 10
#print(strarr[2])

# step 11
#for a in range(len(strarr)): # for a in
range(2)
#print(strarr[a])

# step 12
#for a in strarr: # for a in range(5)
# print(a)'''

# Array valus from python


'''from array import *
arr = array('i',[])
n = int(input("Enter the length of the array"))

for a in range(n):
x = int(input("Enter the Array elements"))
arr.append(x)

print(arr)

search = int(input("Enter the search value"))

k=0
for e in arr:
if e == search:
print(k)
break
k = k+1
# another way
print(arr.index(search))'''

# Numpy intro and install


# Array does not work in multi dimensional
array
# In numpy do not mention typecode
# Types ( Single, Multi, Three Dimensional)

#step 1

'''from array import *


arr = array('i', [1,2,3], [4,5,6])
print(arr)'''

#step 2
# pip - it is a used for install packages
# it is stands for Preferred Installer Program
# settings - interpreter - + - numpy - install

'''from numpy import *


arr = array([1,2,3])
print(arr)'''
#step 3
# creating array using numpy
# 6 ways creating array
# array(), linspace(), logspace(), arange(),
zeros(), ones()

# array()
'''from numpy import *
arr = array([1,2,3,4,5])
print(arr)
print(arr.dtype)
arr = array([1,2,3,4,5.0]) # one value
convert to float all the values converted
# it is called implicit conversion
print(arr.dtype)
print(arr)
arr = array([1,2,3,4,5],float) # int to float
print(arr)
arr = array([1.0,2.0,3.3,4.5,5.0],int) # float
to int
print(arr)'''

# linspace()
'''from numpy import *
arr = linspace(0,15,16) # start, stop,
stepbreak
print(arr) # all the values
float, because break the parts equally
a = linspace(0,15) # by default 50 steps
print(a)'''

# arange
'''from numpy import *
arr = arange(0,15,2) # start, stop, stepsize
print(arr)'''

# logspace
'''from numpy import *
arr = logspace(1,40,5) # seperate the parts
depending the log value
print(arr)'''

# Zeros
'''from numpy import *
arr = zeros(5) # number of repeated elements
print(arr)
arr = zeros(5,int)
print(arr)'''

# Ones
'''from numpy import *
arr = ones(5)
print(arr)
arr = ones(5,int)
print(arr)'''

# step 4
# copying array- one array create from
existing array

'''from numpy import *


arr = array([1,2,3,4,5])
arr = arr+5
print(arr)'''

'''from numpy import *


arr1 = array([1,2,3,4,5])
arr2 = array([6,7,9,4,5])
arr3 = arr1+arr2 # vectrorized operation
print(arr3)'''

# apply some operation

'''from numpy import *


arr1 = array([1,2,3,4,5])
print(sin(arr1))
print(cos(arr1))
print(tan(arr1))
print(max(arr1))
print(min(arr1))
print(sum(arr1))
print(sqrt(arr1))
print(log(arr1))'''

# concat 2 arrays
'''from numpy import *
arr1 = array([1,2,3,4,5])
arr2 = array([6,7,9,4,5])
print(concatenate([arr1,arr2]))'''

# copy array to array


'''from numpy import *
arr1 = array([1,2,3,4,5])
arr2 = arr1
print(arr1)
print(arr2)
print(id(arr1))
print(id(arr2)) # aliasing - same memory add
for both variables'''

# another method view- shallow copy


'''from numpy import *
arr1 = array([1,2,3,4,5])
arr2 = arr1.view()
print(arr1)
print(arr2)
arr1[1]=7
print(arr1)
print(arr2)
print(id(arr1))
print(id(arr2)) # storing diff memory address
but reassign in one array another array also
affect'''

# another method copy- Deep copy


'''from numpy import *
arr1 = array([1,2,3,4,5])
arr2 = arr1.copy()
print(arr1)
print(arr2)
arr1[1]=7
print(arr1)
print(arr2)
print(id(arr1))
print(id(arr2))'''

# matrices
'''from numpy import *
arr1 = array([
[1,2,3],
[4,5,6]
])

print(arr1)
print(arr1.dtype) # datatype
print(arr1.ndim) # dimensional of the array
print(arr1.shape) # row, coloumn
print(arr1.size) # size of the entire
block'''
# convert two dimension to one dimension
'''from numpy import *
arr1 = array([
[1,2,3],
[4,5,6]
])
arr2 = arr1.flatten()
print(arr2)'''

# convert one dimension to two and three


dimension
'''from numpy import *
arr1 = array([
[1,2,3,4,5,6,7,8]
])
arr2 = arr1.reshape(4,2) # convert 2
dimensional
arr3 = arr1.reshape(2,2,2) # convert 3
dimensional
print(arr2)
print(arr3)'''

# create matrix using through array function


'''from numpy import *
arr1 = array([
[1,2,3,4],
[5,6,7,8]
])
m= matrix(arr1)
print(m) # same answer
came'''

# create matrix using matrix function


'''from numpy import *
m = matrix('2 3 4 ; 5 6 7 ; 8 9 1')
print(m)
print(m.diagonal())
print(m.min())
print(m.max())
print(m.sum())'''

# multiply 2 matrix's
'''from numpy import *
m1 = matrix('2 3 4 ; 5 6 7 ; 8 9 1')
m2 = matrix('5 3 6 ; 3 9 7 ; 7 6 3')
m3 = m1+m2
print(m3)
m4 = m1*m2
print(m4)'''

# function
# splitting large number of codes or repeated
codes
# Function ex (User Defined Function)
'''def add():
a=int(input("enter a"))
b=int(input("enter b"))
c= a+b
print("sum of a & b", c)
add() # function call
print("Welcome to scion")
print("Welcome to python")
#add() # second time function call'''

# predefined function or inbuilt function


'''import math
n=int(input("enter the number = "))
print(math.sqrt(n))
print(math.pow(2,2))'''
'''def add_sub(x,y):
a = x+y
b = x-y
return a,b
r1,r2 = add_sub(10,5)
print(r1,r2)'''

'''# pass by value


def upadte(x):
x =8
print(x)
upadte(10) # passing the value to the
function

# pass by reference
def upadte(x):
print(id(x))
x = 8
print(id(x))
print(x)
a= 10
print(id(a))
upadte(a) # pass by reference
print(a)

# Call by reference in Python Passing Mutable


Object (String)
def change_string(str):
str = str + " How is you"

print("printing the string inside function :",
str)
string1 = "Hi I am there"
change_string(string1)
#calling the function
print("printing the string outside function :",
string1)

# Call by reference Passing Immutable Object


(List)
def changelist(list1):
list1.append(20)
list1.append(30)
print("list inside function = ", list1)
list1=[10,30,40,50] #defining the list
changelist(list1) #calling the function 
print("list outside function = ", list1)
'''
# Function arguments or function parameters

'''def add(a,b): # Formal parameters


c = a+b
print(c)
add(5,4) # Actual parameters
add(7,8) # Actual parameters

# Actual parameters having 4 types of arguments

# Required arguments
add(6) # Error in Required arguments'''

# Keyword Arguments
'''def display(name, marks):
print("The Name is = ", name)
print("The Mark is = ", marks)
display(name="abc", marks=70)
display(marks=90, name="xyz")'''

# default arguments
'''def add(a=10,b=5):
c = a+b
print(c)
add(6,8)
add(7)
add(b=6)
add()'''

# Variable Length Argument ( in single


variable passing multiple values)
'''def add(*a):
sum = 0
for i in a:
print(i)
sum=sum+i
print(sum)
add(3,4,5,6,7)'''

'''def add(a,*b):
print(a)
print(b) # print tuple format
add(3,4,5,6,7)'''

# keyword Variable Length Argument

'''def person(name, **b):


print(name)
print(b)

person("scion", age = 12, city = "Thanjavur",


Mobile = 9597754497)'''

'''def person(name, **b):


print(name)
for i,j in b.items():
#print(i,j)
#print(i)
print(j)

person("scion", age = 12, city = "Thanjavur",


Mobile = 9597754497)'''

# global variable
#step 1

'''a =10
def fun():
a=15
print("in fun", a)
fun()
print("out fun",a)'''

# step 2
'''a =10
print(id(a))
def fun():
global a
a=15
print("in fun", a)
print(id(a))
fun()
print("out fun",a)
print(id(a))'''

# step 3
'''a =10
def fun():
a=15
x = globals()['a']
print("in fun", a)
print(id(a))
print("x",x)
print(id(x))
fun()
print("out fun",a)
print(id(a))'''

#step 4
'''a =10
def fun():
a=9
print("in fun", a)
print(id(a))
globals()['a'] = 15

fun()
print("out fun",a)
print(id(a))'''

# pass list to a function

'''def count(lst):
even = 0
odd = 0
for i in lst:
if i%2 == 0:
even+=1
else:
odd+=1

return even,odd

lst = [23,34,56,67,89,35,58]
even,odd = count(lst)
print(even)
print(odd)'''

# fibanocci series
# 0 1 1 2 3 5 8 13 21...

# step 1
'''def fib(n):

a = 0
b = 1

print(a)
print(b)

fib(10)'''
# step 2
'''def fib(n):
a = 0
b = 1

print(a)
print(b)

for i in range(2,n):
c = a+b
a = b
b = c
print(c)

fib(10)'''

# step 3 - fib(1)
'''def fib(n):
a = 0
b = 1

print(a)
print(b)
for i in range(2,n):
c = a+b
a = b
b = c
print(c)

fib(1) # ask 1 number but came 2 numbers in


output'''

# step 4 - fib(1)
'''def fib(n):
a = 0
b = 1
if n ==1:
print(0)
else:
print(a)
print(b)

for i in range(2,n):
c = a+b
a = b
b = c
print(c)
fib(1)'''

# factorial
# 5! = 5*4*3*2*1
# step 1
'''x = 5
result = fact(x)
print(result)'''

#step 2

'''def fact(n):
f = 1
for i in range(1,n+1):
f = f*i
return(f)

x = 5
result = fact(x)
print(result)'''

# Recursion function - calling itself


# step 1
'''def greet():
print("Welcome")
greet()'''

# step 2

'''def greet():
print("Welcome")
greet() # recursion
greet()'''

# step 3
'''import sys
print(sys.getrecursionlimit())
def greet():
print("Welcome")
greet() # recursion
greet()'''

# step 4
'''import sys
sys.setrecursionlimit(2000)
print(sys.getrecursionlimit())
i=0
def greet():
global i
i = i+1
print("Welcome", i)
greet() # recursion
greet()'''

# factorial using recursion

'''def fact(n):

if n==0:
return 1

return n * fact(n-1)

result = fact(5)
print(result)'''
# Anonymous function or Lambda function
# it is a function defined without a name
# lambda argument: expression
'''a = lambda a,b : a+b
print(a(15,20))'''
'''add = lambda a,b : a+b
num1=int(input("Enter the first number : "))
num2=int(input("Enter the second number : "))
print(add(num1,num2))'''

# filter,map,reduce using lamda function

'''from functools import reduce

a = [3,4,5,6,8,9]

evens = list(filter(lambda n:n%2==0,a))


print(evens)

doubles = list(map(lambda n:n*n,evens))


print(doubles)
sum = reduce(lambda a,b:a+b, doubles)
print(sum)'''

# Decorators - change the behaviour of the


existing function using new function

#step 1
'''def div(a,b):
print(a/b)
div(4,2)
div(2,4)''' # user side swap

#step 2
'''def div(a,b):
if a<b: # distrubing in
function
a,b = b,a
print(a/b)
div(4,2)
div(2,4)'''

#step 3
'''def div(a,b):
print(a/b)

def div1(func): # decorators


def inner(a,b):
if a<b:
a,b = b, a
return func(a,b)
return inner

div = div1(div)
div(2,4)'''

# Module - create function as a module using


and import anywhere
# create small small parts from large number
of codes
# Syntax - from filename import*
# save function.py
'''def add(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def sub(a,b):
return a/b'''

# save module.py
'''from function import add
# from function import *
a = int(input("Enter the number of a: "))
b = int(input("Enter the number of b: "))
print(add(a,b))'''

# Special variable __name__


# demo.py
# step1
#print(__name__) # __main__ - static point of
execution

# step2
#import calc
#print("Demo syas : "+ __name__)

# step3
'''print("welcome")
print("User")'''

'''def main():
print("welcome")
print("User")
main()'''

'''def main():
print("welcome")
print("User")
if __name__ == "__main__"
main()'''

# calc.py
# step 2
#print("welcome" + __name__)

# step 3
# import demo
#print("it is time to calculate")

# another example
# demo.py
# step 1
'''def fun1():
print("function 1 is call")
def fun2():
print("function 2 is call")
fun1()
fun2()'''

# step 2
'''def fun1():
print("function 1 is call")
def fun2():
print("function 2 is call")
def main():
fun1()
fun2()
main()'''

# step 4
'''from calc import add
def fun1():
add()
print("function 1 is call")
def fun2():
print("function 2 is call")
def main():
fun1()
fun2()
main()'''
# calc.py
# step 3
'''def add():
print("result 1 is call")
def sub():
print("result 2 is call")
def main():
print("in calc main")
add()
sub()
main()'''

# step 5
'''def add():
print("result 1 is call", __name__)
def sub():
print("result 2 is call")
def main():
print("in calc main")
add()
sub()
if __name__ == "__main__"
main()'''

# Fruitful Function ( It is having a return


value)
'''def add(a,b):
c = a+b
return c
d= add(5,4)
print("The value of addition", d) # it is given
the out for function call'''

# Another Example
'''def add(a,b):
c = a+b
return c
def sub(d,f):
e = d-f
return e
def mul(c,e):
i = c*e
print("The result is = ", i)
x=add(3,4)
y=sub(7,4)
mul(x,y)'''

# Function Composition
'''def add(a,b):
c = a+b
return c
def sub(d,f):
e = d-f
return e
def mul(c,e):
i = c*e
print("The result is = ", i)
mul(add(3,4),sub(7,4)) # One function call
using a argument of another funtion call'''

# Function Example
'''def add(a,b):
c= a+b
print(c)
def sub(a,b):
c= a-b
print(c)
def mul(a,b):
c= a*b
print(c)
def div(a,b):
c= a/b
print(c)
def area(radius):
a=3.14*radius*radius
print(a)
def circumference(radius):
a=2*3.14*radius
print(a)
def simpleinterest():
p=int(input("enter the principle"))
n = int(input("enter the tenure"))
r = int(input("enter the rate of
interest"))
si=(p*n*r)/100
print(si)

# user.py
from function import*
def user():
print("1 for add")
print("2 for sub")
print("3 for mul")
print("4 for div")
print("5 for area")
print("6 for circumferences")
print("7 for interest")
choice = int(input("Enter your choice: "))
if(choice==1 or choice==2 or choice==3 or
choice==4):
a=int(input("Enter the first element :
"))
b=int(input("Enter the second element :
"))
if(choice==1):
add(a,b)
if(choice==2):
sub(a,b)
if(choice==3):
mul(a,b)
if(choice==4):
div(a,b)
if(choice==5 or choice==6):
radius=float(input("Enter the radius"))
if(choice==5):
area(radius)
if(choice==6):
circumference(radius)
if(choice==7):
simpleinterest()
print("continue[Yes/No]")
c=input()
if(c=="yes"):
user()

user()'''

# Lists - Already known as other languages


name of array
# It is the container
# it holds comma seperated values(items or
elements) between square brackets
# it is holding various datatype elements
differ from array
'''Fruits=["banana","graphs","apple"]
print(Fruits)
print(type(Fruits))
Li=["welcome", 2.30, 5, 5+6j, True]
print(Li)
print(Li[1]) # call from index value
Li[1]=5.20
print(Li)
print(type(Li))
#Li.append(False)
#print(Li)'''

'''
>>> list = [12,34,78,95,56]
>>> list
[12, 34, 78, 95, 56]
>>> list[0]
12
>>> list[4]
56
>>> list[1:]
[34, 78, 95, 56]
>>> list[-3]
78
>>> list1= ["shan","sana","nila","navin"]
>>> list1
['shan', 'sana', 'nila', 'navin']
>>> list2 = ["hi", 10.5, 34, 5+5j]
>>> list2
['hi', 10.5, 34, (5+5j)]
>>> list3 = [list,list1]
>>> list3
[[12, 34, 78, 95, 56], ['shan', 'sana', 'nila',
'navin']]
>>> list.append(63)
>>> list
[12, 34, 78, 95, 56, 63]
>>> list.insert(3,45)
>>> list
[12, 34, 78, 45, 95, 56, 63]
>>> list.remove(95)
>>> list
[12, 34, 78, 45, 56, 63]
>>> list.pop(2)
78
>>> list
[12, 34, 45, 56, 63]
>>> list.pop()
63
>>> del list[3:]
>>> list
[12, 34, 45]
>>> list.extend([13,35,46])
>>> list
[12, 34, 45, 13, 35, 46]
>>> max(list)
46
>>> min(list)
12
>>> sum(list)
185
>>> list.sort()
>>> list
[12, 13, 34, 35, 45, 46]
>>>
'''

# Tuples - It is same as list but its


immutable
# between open bracket and close bracket
# its execute faster than lists
'''Li=("welcome", 2.30, 5, 5+6j, True)
print(Li)
print(type(Li))
#Li.append(False)
#print(Li)'''
'''
>>> tuple = (39,45,65,78,76)
>>> tuple
(39, 45, 65, 78, 76)
>>> tuple[2]
65
>>> tuple[1]=43
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
tuple[1]=43
TypeError: 'tuple' object does not support item
assignment
'''

# set
# it is not maintained the sequence
'''
>>> set = {22,45,56,78,98}
>>> set
{98, 45, 78, 22, 56}
>>> s[3] # it is not
possible getting value from index, because it's
not sequence
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
s[3]
NameError: name 's' is not defined
>>> set.add(43)
>>> set
{98, 43, 45, 78, 22, 56}
>>> set = {22,45,56,78,98,98}
>>> set
{98, 45, 78, 22, 56}
Days={"Monday","Tuesday","Wednesday","Thursday"
,"Friday","Saturday","Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
'''

# Dictionaries - it is also container using


key-value concept
# elements between the curly braces
# where key and values are python datatypes

'''a={"id":2,"name":"abc","dept":"cse"}
print(type(a))
print(a)
print(a["id"]) # call from key value
a["name"]="xyz"
print(a)'''

# OOPS Concept
# Object - Everything is object it having
properties(identity, state, behaviour) or
(Attributes, behaviour)
# Variable (Attributes) - Holds some value
# Method or Function (Behaviour) - Functioning
object through this

# Class - Blueprint
# Object - Instance or copy or Duplicate

'''class computer:
# Attributes
# Behaviour
def abc(self):
print("The machine is : i3, 2GB RAM,
1TB HDD")

#a= 8 # variable or attribute,


here a is object
#print(type(a)) # type "int" , inbuilt
class

b=computer() # object creation


b.abc() # behaviour or class or
method based on object
# computer.abc(b) # another type of function
call through self argument
print(type(b)) # here computer our class
d=computer()
computer.abc(d) # Passing second object'''

# inbulit function how it is work


'''a=16
print(a.bit_length())'''

'''class abc:

def __init__(self,processor,ram):
# Constructor
self.proc = processor
self.ram = ram

def display(self):
print("Processor is : ", self.proc,
"Ram is : ", self.ram)

a=abc("i3", 8)
# Constructor call
b=abc("i5", 16)
# (self = b, processor = "i5", ram = 16)
a.display() # Every objects
having and binding own method and variable
b.display()'''

# Constructor
'''class abc():
pass
a=abc()
b=abc()
print(id(a)) # heap memory
address
print(id(b)) # it having
different memory'''

# when create the object that time called


constructor
# it is one of the define function
# it is temporary function after the process
it is destruct the function
# it is reduce and save the memory space
# Every time you create an object it is
allocated to new space
# Size of the objects - depends on the no.of
variables and size of the variables
# who allocates the size of the object -
constructor

# constructor without argument


'''class abc:
def __init__(self): #
Constructor call
print("welcome to constructor")
def getnumber(self):
#num=int(input("Enter the number")) #
Local variable
self.num=int(input("Enter the number"))
# Instance variable or this variable creating
for class
def printnumber(self):
#print("print the entered number", num)
# Error
print("print the entered number",
self.num)
x=abc() #
object creation - constructor called
x.getnumber()
x.printnumber()'''

# constructor with argument or parameterized


constructor
'''class abc:
def __init__(self,fn,sn): # fn,sn for
constuctor
self.a=fn # constructor
a change to a for class
self.b=sn # constructor
b change to b for class

def printnumber(self):
self.c = self.a+self.b
print("The result is = ", self.c)
x=abc(40,50) #
constructor call to variable assign to class
x.printnumber()'''
# Constructor overloading
# Argument having the default value
# Overload the constructor
'''class abc:
def __init__(self,a=0,b=0):
print(a + b)
print(b)
x=abc(b=10)
y=abc(10,20)'''

'''class xyz:
def __init__(self,name,officename="SCION"):
print("Hi", name)
print("Welcome to our office",
officename)

a=xyz("sana")
b=xyz("niraza","armada")'''

# Multiple Constructor
'''class xyz:
def __init__(self):
print("1 st constructor")
def __init__(self):
print("2 st constructor")
def __init__(self):
print("3 rd constructor")
a=xyz()'''

# Destructor- clear the memory from used


constructor

'''class xyz:
def __init__(self,name,officename="SCION"):
print("Hi", name)
print("Welcome to our office",
officename)
def __del__(self):
print("Destructor is called")

a=xyz("niraza","armada")
#a=xyz("niraza","armada") # Destructor
already clear the memory
del a # Object
deleted
#a=xyz("niraza","armada")
#print("Object deleted")'''

# self - it is a pointer where is go


'''class abc():
def __init__(self):
self.name = "shan"
self.age=33
def update(self): # pointing for b object
self.age=34
#def compare(self,age1): # compare(who is
calling, whom to compare)
#self.age=age1

a=abc()
b=abc()
print(a.name,a.age)
print(b.name,b.age)
b.update() # b object going update
self parameter directing to b
if a.age==b.age: # here a is self, b is
others, if you want doing reverse also
print("they are same")
else:
print("They are different")
print(b.name,b.age)'''

# Variable
# Types
# Instance variable
# Class or static variable

'''class car:

wheels = 4 # class
variable or static variable

def __init__(self):
self.mileage = 23 # instance
variable, it is differ for different object
self.company = "BMW" # instance
variable, it is differ for different object

car1 = car()
car2 = car()
print(car1.mileage," ", car1.company," ",
car1.wheels)
print(car2.mileage," ", car2.company," ",
car2.wheels)
car2.mileage = "24"
car2.company = "Audi" # if you
changed in one obj not affecting the other
objects
car.wheels = 5 # this
change affects all objects
print(car2.mileage," ", car2.company," ",
car2.wheels)
print(car1.mileage," ", car1.company," ",
car1.wheels)'''

# Types of methods in python


# Methods are behaviour
# 1. Instance methods
# 2. Class Methods
# 3. Static methods

'''class student():
college = "scion"

def __init__(self,m1,m2,m3):
self.m1 = m1
self.m2 = m2
self.m3 = m3

#@instancemethod #
this method accessing instance variable
def avg(self):
return (self.m1+self.m2+self.m3)/3

@classmethod #
this method accessing class variable
def getdetails(cls):
return cls.college

@staticmethod #
this method not using class and instance
variable
def info():
print(" This is a student class......")
s1=student(54,45,65)
s2=student(67,76,87)
print(int(s1.avg()))
print(s2.avg())
print(student.getdetails())
student.info()'''

#inner class in pyhton


# class inside the variable and methods
# class inside the class?

# you can create object of the inner class


inside the outer class
# (or) you can create object of the inner
class outside the outer class provided you use
outer class name to call it

'''class student: # outer


class

def __init__(self,name,rollno):
self.name= name
self.rollno=rollno
#self.lap = self.laptop() # you can
create object of the inner class inside the
outer class

def info(self):
print(self.name, self.rollno)
#self.lap.info()

class laptop: # inner


class
def __init__(self):
self.brand = "HP"
self.proc = "i3"
self.ram = 8
def info(self):
print(self.brand, self.proc,
self.ram)

s1= student("shan", 1)
s2= student("scion", 2)
s1.info()
s2.info()
s3= student.laptop()
#you can create object of the inner class
outside the outer class provided you use outer
class name to call it
s3.info()'''

# inheritance
# parent- child relationship
# ex: parents house or mobile it is mine
# but its mine not for parents
# Inheritance - functions derived from one
class to other class
# Single Inheritance
'''class A:
def abc(self):
print("This is class of A")

class B(A):
def xyz(self):
print("This is class of B")

obj = B()
obj.abc()
obj.xyz()'''
# Example

'''class student:
def GetStudentDetails(self):
self.rollno = input("RollNo : ")
self.name=input("Name : ")
self.fathername=input("Father Name : ")
self.age=input("Enter the Age : ")
def PrintDetails(self):
print("Roll No : ",self.rollno)
print("Name : ", self.name)
print("Father Name : ",
self.fathername)
print("Age is : ", self.age)

class marks(student):
def GetMarkDetails(self):
self.tamil=int(input("Enter the Tamil
Marks : "))
self.English = int(input("Enter the
English Marks : "))
self.Maths = int(input("Enter the Maths
Marks : "))
self.Science = int(input("Enter the
Science Marks : "))
self.Social = int(input("Enter the
Social Marks : "))

def result(self):
self.total =
self.tamil+self.English+self.Maths+self.Science
+self.Social
self.average = self.total/5
if(self.average>=90):
self.grade="S"
elif(self.average>=80):
self.grade = "A"
elif (self.average >= 70):
self.grade = "B"
elif (self.average >= 60):
self.grade = "C"
elif (self.average >= 50):
self.grade = "D"
else:
self.grade = "Fail"

def PrintMarkDetils(self):
print("Total : ", self.total)
print("Average : ", self.average)
print("Grade : ", self.grade)

obj = marks()
obj.GetStudentDetails()
obj.PrintDetails()
obj.GetMarkDetails()
obj.result()
obj.PrintMarkDetils()'''

# Multilevel Inheritance
'''class base:
Functions
class Derivedone(base):
Functions
class Derivedsecond(Derivedone):
Functions'''

'''class A:
def a(self):
print("This is class A")
class B(A):
def b(self):
print("This is class B")
class C(B):
def c(self):
print("This is class C")

obj= C()
obj.a()
obj.b()
obj.c()'''

# Bank Example
'''class bank:
def getDetails(self):
self.accountno = input("Enter the
account number : ")
self.accountname = input("Enter the
Name : ")
self.accounttype = input("Enter the
Account type : ")
def printAccDetails(self):
print("Account Number : ",
self.accountno)
print("Account Holder Name : ",
self.accountname)
print("Account type : ",
self.accounttype)

class deposit(bank):
balance = 500
def getDepositeDetails(self):
self.amount = int(input("Enter the
amount : "))
self.balance = self.amount+self.balance

def printDepositeDetails(self):
print("Your Current Balance is :",
self.balance)

class withdraw(deposit):
def getWithdrawDetails(self):
self.amount = int(input("Enter your
need amount"))
self.balance = self.balance-self.amount

def printWithdrawDetails(self):
print("Your Current Balance is :",
self.balance)

obj= withdraw()
obj.getDetails()
obj.printAccDetails()
obj.getDepositeDetails()
obj.printDepositeDetails()
obj.getWithdrawDetails()
obj.printWithdrawDetails()'''

# Multiple Inheritance
'''class base:
functions
class Derivedone:
functions
class Derivedtwo(base,Derivedone):
functions'''

'''class A:
def a(self):
print("This is class A")
class B:
def b(self):
print("This is class B")
class C(A,B):
def c(self):
print("This is class C")
obj=C()
obj.a()
obj.b()
obj.c()'''

# Example (Multiple Inheritance)


'''class bank:
def getDetails(self):
self.accountno = input("Enter the
account number : ")
self.accountname = input("Enter the
Name : ")
self.accounttype = input("Enter the
Account type : ")
def printAccDetails(self):
print("Account Number : ",
self.accountno)
print("Account Holder Name : ",
self.accountname)
print("Account type : ",
self.accounttype)

class deposit():
balance = 0
def getDepositeDetails(self):
self.amount = int(input("Enter the
amount : "))
self.balance = self.amount+self.balance

def printDepositeDetails(self):
print("Your Current Balance is :",
self.balance)

class withdraw(bank,deposit):
def getWithdrawDetails(self):
self.amount = int(input("Enter your
need amount"))
self.balance = self.balance-self.amount

def printWithdrawDetails(self):
print("Your Current Balance is :",
self.balance)

obj = withdraw()
obj.getDetails()
while(True):
print("1 for deposite")
print("2 for withdraw")
choice = int(input("Enter the choice : "))
if(choice == 1):
obj.getDepositeDetails()
obj.printDepositeDetails()
if(choice == 2):
obj.getWithdrawDetails()
obj.printWithdrawDetails()
print(" Continue(yes/no)")
c= input()
if c== "yes":
continue
else:
break'''

# constructor in inheritance
# Constructor behaviour in inheritance
# How does super methods works
# Method resolution order

'''class A:
def __init__(self):
print(" constructor for A ")

def version1(self):
print(" version 1 is called ")

def version2(self):
print(" version 2 is called ")

class B(A):
#def __init__(self):
#super().__init__()
#print(" constructor for B ")

def version3(self):
print(" version 3 is called ")

def version4(self):
print(" version 4 is called ")

#obj = A()
#obj.version1()
#obj.version2()

obj = B() # when you create object of


sub class it will call init of subclass first
# if you have call super then it will first
call init of super class then call it init of
sub class
obj.version1()
obj.version2()
obj.version3()
obj.version4()'''

# Method Resolution Order (MRO)

'''class A:

def __init__(self):
print(" constructor for A ")

def version1(self):
print(" version 1-A is called ")

def version2(self):
print(" version 2 is called ")

class B():
def __init__(self):
print(" constructor for B ")

def version1(self):
print(" version 1-B is called ")

def version4(self):
print(" version 4 is called ")

class C(A,B):
#def __init__(self):
#super().__init__()
#print(" Constrcutor for C ")

def version5(self):
super().version4() # Access
parent class methods using super keyword

obj = C()
# in a tree structure of multiple inheritance,
when call super in c class it called left side
class constructor called
obj.version1()
# MRO - in c class obj called same type of
methods in different classes but it is called
left side class method
obj.version5()'''

# introduction to polymorphism in python


# Many + Form
# in situation changes behave also changes
# objects have multiple form
# Four types (Duck typing, Operator
overloading, Method overloading, Method
overriding)

# Duck Typing - no change argument and method,


only change class

'''class PyCharm:
def execute(self):
print("Compiling")
print("Runing")

class TextEditor:
def execute(self):
print("Spell Check")
print("Easy to Convert")
print("Compiling")
print("Runing")

class laptop:
def code(self,ide):
ide.execute()

#ide = PyCharm() # This is Duck


ide = TextEditor() # This is a bird
like a duck

obj = laptop()
obj.code(ide)'''

# Operator overloading

'''a = 5
b = 6.5
c = "scion"
d = " r and d"
print(a + b)
#print(a + c) # unsupported operand
type(s) for +: 'int' and 'str'
print(c + d)'''

'''a=5
b=6
c = "scion"
d = " r and d"
print(a + b)
print(c + d)
print(int.__add__(a,b)) # Magic methods
like sub,mul,div...etc..
print(str.__add__(c,d))'''

'''class student:

def __init__(self,m1,m2):
self.m1 = m1
self.m2 = m2

def __add__(self, other): # operator


overload
m1 = self.m1 + other.m1
m2 = self.m2 + other.m2
s3 = student(m1,m2)
return s3

def __gt__(self, other):


r1 = self.m1+self.m2
r2 = other.m1+other.m2
if r1>r2:
print("s1 wins")
else:
print("s2 wins")

s1 = student(66,65)
s2 = student(56,56)
s3 = s1 + s2 # unsupported operand type(s)
for +: 'student' and 'student'
# integer and know the '+' but student class
does not know the '+', same as all arithmetic
operators
print(s3.m1,s3.m2)
student.__gt__(s1,s2)'''
# Method overloading
# in other language defn - same method name,
different argument in single class)
'''class abc():
def sum(self,a,b):
s= a + b
print(s)
def sum(self,a,b,c):
s= a+b+c
print(s)

obj = abc()
obj.sum(10,20)
obj.sum(20,30,40)'''

# But here

'''class abc():

def sum(self,a=None,b=None,c=None):
s=0
if a!=None and b!=None and c!=None:
s= a+b+c
elif a!=None and b!=None:
s=a+b
else:
s=a
return s

obj = abc()
print("The result is ",obj.sum())
print("The result is ",obj.sum(10))
print("The result is ",obj.sum(10,20))
print("The result is ",obj.sum(10,20,30))'''

# Method overriding
# same method name, same arguments, in
different classes (Through inheritance
concept)

'''class A():
def mobile(self):
print("My mobile is samsung")

class B(A):
def mobile(self):
print("My mobile is apple")
obj = B()
obj.mobile()'''

# iterator - iterating the list or any other


function
# till now using for loop
'''lst = [1,2,3,4,5]
for i in lst:
print(i)'''

# here using two functions iter and next


'''lst = [1,2,3,4,5]
l = iter(lst)
print(next(l)) # this one way
print(l.__next__()) # another way
print(l.__next__())
print(l.__next__())
print(l.__next__())
print(l.__next__()) # StopIteration'''

# building own iterator


'''class pow:
def __init__(self,max=0):
self.max = max
def __iter__(self):
self.num = 0
return self
def __next__(self):
if self.num< self.max:
result = 2**self.num
self.num += 1
return result

else:
raise StopIteration

a = pow(5)
i= iter(a)
print(next(i))
print(next(i))
print(next(i))
print(next(i))
print(next(i))
print(next(i))

#for i in pow(5):
#print(i)'''
# generators - generate the iterator into
function
# step 1
'''def demo():
#return 5
yield 5
a= demo()
print(a) # <generator object demo at
0x0000010DDD1A62B0>'''

# step 2
'''def demo():
yield 5
a= demo()
print(a.__next__())'''

# step 3
'''def demo():
n = 1
while n<=10:
a= n * n
yield a
n+=1
result = demo()
print(next(result))
print(next(result))
print(next(result))

for i in demo():
print(i)'''

# Exception Handling
# try, catch, throw (Exception handling)
# Compile time error, developer mistake
(Syntax error - (: colon missing))
# Logical error, developer mistake - wrong
result came
# Run time error, user mistake - one error
affect all the program affect
li=[1,3,4,5]
#print(li[0])
#print(li[4]) #IndexError: list index
out of range
#print(lx[4]) #NameError: name 'lx' is
not defined
#print(5+"5") #TypeError: unsupported
operand type(s) for +: 'int' and 'str'
#print(6/0) #ZeroDivisionError:
division by zero
'''import math
math.sqrt(-5)''' #ValueError: math domain
error

'''a=5
b=2
print(a/b) # Critical statement
print("bye")''' # Normal statement

'''a=5
b=0
print(a/b) # ZeroDivisionError:
division by zero
print("bye")'''

'''a=5
b=0
try:
print(a/b)
except Exception as e:
print("Exception : ",e)
print("bye")'''
# if file open finally closed
# if database open finally close
# Ex- if fridge open then close

'''a=5
b=2
try:
print("File open")
print(a/b)
#print("File close")
except Exception as e:
print("Exception : ", e)
#print("File close")
finally: # Finally block will be
executed if we get error as well as not get
error
print("File close")'''

# Multithreading - execute the process


simultaneously

# step 1
'''class Hello:
def run(self):
for i in range(5):
print("Hello")

class Hi:
def run(self):
for i in range(5):
print("Hi")

t1= Hello()
t2= Hi()

t1.run()
t2.run()'''

# step 2
'''from threading import *
class Hello(Thread):
def run(self):
for i in range(15):
print("Hello")

class Hi(Thread):
def run(self):
for i in range(15):
print("Hi")

t1= Hello()
t2= Hi()
#t1.run()
#t2.run()
t1.start()
t2.start()'''

# step 3
'''from time import sleep
from threading import *
class Hello(Thread):
def run(self):
for i in range(5):
sleep(1)
print("Hello")
class Hi(Thread):
def run(self):
for i in range(5):
sleep(1)
print("Hi")

t1= Hello()
t2= Hi()
#t1.run()
#t2.run()
t1.start()
sleep(0.3)
t2.start() ''' # three threads main,t1,t2'''

# step 4
'''from time import sleep
from threading import *
class Hello(Thread):
def run(self):
for i in range(5):
sleep(1)
print("Hello")
class Hi(Thread):
def run(self):
for i in range(5):
sleep(1)
print("Hi")

t1= Hello()
t2= Hi()
#t1.run()
#t2.run()
t1.start() # thread start here
sleep(0.3) # avoid collision
t2.start()

#print("bye") # it is appear in main thread


thatswhy printing first

t1.join()
t2.join()
#print("bye")'''

# File handling
# create and write in to file
'''f = open("scion",'w')
f.write("welcome to scion\n")
f.write("welcome to python")
print("success")'''

# read data from existing file


#f= open("scion",'r')
#print(f.read())
#print(f.read(4))
#print(f.readline())
#print(f.readlines())

# append the data existing file


'''f = open("scion",'a')
f.write("\nhi hello welcome")'''

# read the data using for loop


'''f= open("scion",'r')
for i in f:
print(i)
#print(i,end="")'''
# copy data one file to another file
'''f = open("scion",'r')
f1 = open("scion1",'w')

for data in f:
f1.write(data)'''

# read image file


'''f = open("sana.jpg",'rb')
for i in f:
print(i)'''

# copy img file to another file


'''f = open("sana.jpg",'rb')
f1= open("sana1.jpg",'wb')
for img in f:
f1.write(img)'''

# Linear search
# no need maintain order
# using for loop
'''def search(lst,n):
for i in lst:
if i == n:
return True
else:
return False

lst = [2,3,5,6,7,8]
n = 9

if search(lst,n):
print("Found")
else:
print("Not found")'''

# using while loop

'''pos = -1
def search(lst,n):
i = 0
while i<len(lst):
if lst[i] == n:
globals()['pos'] = i
return True
i = i + 1
else:
return False

lst = [2,3,5,6,7,8]
n = 7

if search(lst,n):
print("Found at", pos + 1)
else:
print("Not found")'''

# Binary Search
# should follow the sorting order
'''pos = -1
def search(lst,n):
l = 0 # lower bound
u = len(lst)- 1 # Upper bound
while l<=u:
mid = (l+u)//2
if lst[mid]== n:
globals()['pos'] = mid
return True
else:
if lst[mid]<n:
l = mid + 1
else:
u = mid + 1
return False

lst = [7,8,9,10,11]
n = 8

if search(lst,n):
print("Found at", pos + 1)
else:
print("Not found")'''

# bubble sort
# sorting number in list
# in do multiple swapping - drawback
'''def sort(lst):
for i in range(len(lst)-1,0,-1):
for j in range(i):
if lst[j]>lst[j+1]:
t = lst[j]
lst[j] = lst[j+1]
lst[j+1] = t

lst = [2,5,7,4,3]
sort(lst)
print(lst)'''

# Selection sort
# compare first and search the min value in
the loop
'''def sort(lst):
for i in range(4):
minpos = i
for j in range(i,5):
if lst[j]<lst[minpos]:
minpos = j
t = lst[i]
lst[i] = lst[minpos]
lst[minpos] = t
#print(lst)
lst = [2,5,7,4,3]
sort(lst)
print(lst)'''
# Data base connection
# MySQL installing and configure
# create database and table
'''show databases;
create database scion;
use scion;
create table student (name varchar(20),dept
varchar(10));
insert into student values ("ravi","cse"),
("raja","ece");
select * from student;'''

# database connect with python


# now mysql-connector installing, it is the
package - bridge of pyrhon and mysql
# settings - interpretor - add package

# step 1
'''import mysql.connector
mydb =
mysql.connector.connect(host="localhost",user="
scion",passwd="1234")'''
# step 2
'''import mysql.connector
mydb =
mysql.connector.connect(host="localhost",user="
scion",passwd="1234")
a = mydb.cursor() # pointing the
database
a.execute("show databases") # write query'''

#step 3
'''import mysql.connector
mydb =
mysql.connector.connect(host="localhost",user="
scion",passwd="1234")
a = mydb.cursor() # pointing the
database
a.execute("show databases") # write query
for i in a:
print(i)'''

# step 4
# show table
'''import mysql.connector
mydb =
mysql.connector.connect(host="localhost",user="
scion",passwd="1234",database="scion1") #
mention db name
a = mydb.cursor() # pointing the
database
a.execute("select * from student") # write
query
for i in a:
print(i)'''

# step 4
# fetching the data
'''import mysql.connector
mydb =
mysql.connector.connect(host="localhost",user="
scion",passwd="1234",database="scion") #
mention db name
a = mydb.cursor() # pointing the
database
a.execute("select * from student") # write
query
x = a.fetchall()
for i in x:
print(i)'''
# fetch one data
'''import mysql.connector
mydb =
mysql.connector.connect(host="localhost",user="
scion",passwd="1234",database="scion") #
mention db name
a = mydb.cursor() # pointing the
database
a.execute("select * from student") # write
query
x = a.fetchone()
for i in x:
print(i)'''

You might also like