Python
Python
Contents
Introduction .......................................................................4
Variables ..........................................................................11
List...................................................................................42
Tuple................................................................................55
Set ...................................................................................60
Dictionary ........................................................................67
Constructor.................................................................... 122
Inheritance..................................................................... 128
CODERZ ACADEMY
Operator Overloading ..................................................... 158
CODERZ ACADEMY
INTRODUCTION
What is Python?
Why it is popular?
It is used for:
CODERZ ACADEMY
Software Development,
Data science,(Math’s)
System Scripting.
Game Programming
Special Features
Interpreter.
Support object oriented programming.
Other libraries attached to python.
Python libraries attached to other languages.
Extension library.
Open source.
Cpython – is a original python version 2.0,3.0 .
OOPS:
Object programming language aims to implement
real time entities like
inheritance,polymorphism,hiding,etc. in
programming.
The main aim of oops to bind together the data
and function
CODERZ ACADEMY
That operates on them so that no other part of the
code can access this data except that function.
CODERZ ACADEMY
Python can be used for rapid prototyping, or for
production-ready software development.
Why Python?
CODERZ ACADEMY
Execute Python Syntax
As we learned in the previous page, Python syntax can
be executed by writing directly in the Command Line:
Python Indentation
Example
if 5 > 2:
print("Five is greater than two!")
CODERZ ACADEMY
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
Comments
Example
Comments in Python:
#This is a comment.
print("Hello, World!")
CODERZ ACADEMY
Multi Line Comments
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!)
CODERZ ACADEMY
VARIABLES
Creating Variables
Example
x=5
y = "John"
print(x)
print(y)
Example
CODERZ ACADEMY
single or Double Quotes?
Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive
Example
a=4
A = "Sally"
print(a)
print(A)
CODERZ ACADEMY
RULES
Example
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
CODERZ ACADEMY
Example
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
Camel Case
myVariableName = "John"
CODERZ ACADEMY
Pascal Case
MyVariableName = "John"
Snake Case
my_variable_name = "John"
CODERZ ACADEMY
Example
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
CODERZ ACADEMY
DATA TYPES
CODERZ ACADEMY
String
a='hai'
print(a)
a="hai"
print(a)
integer
a=1
b=2
c=3
print(a+b+c)
float
a=10.5
b=20.5
c=a+b
print( c)
CODERZ ACADEMY
PREDEFINED FUNCTION
type conversion
input function
Isinstance function
type function
type conversion
int(), float(),str() are the functions used to convert
respective types
Eg:1
a='2'
b='3'
c=a+b
print(c)
print(int(a)+int(b))
Eg:2
a='2.25'
CODERZ ACADEMY
b='3.23'
print(float(a)+float(b))
Eg:3
a=2
b=3
print(str(a)+str(b))
input function:
to get values (input) from users
all inputs are in string format
Eg:1
Eg:2
CODERZ ACADEMY
Eg 2.1:
print(int(input("enter a number: "))+ int(input("enter a
number: ")))
Eg:3
z="*"*20
print(z)
z="12"*2
print(z)
Eg:4
z="PYTHON"*int(input("enter a number"))
print(z)
Isinstance function:
syntax: isinstance(variable_name,datatype)
to check whether the given variable belongs to given
datatype , if yes return "True" else "False"
CODERZ ACADEMY
Eg:1
c=5+3j
print(isinstance(c,complex))
a=34
print(isinstance(a,int))
z=34.5
print(isinstance(z,complex))
type function:
Eg:1
z=12
print(type(z))
Eg:2
z=1.2
CODERZ ACADEMY
print(type(z))
Eg:3
z="12"
print(type(z))
Eg:4
z="Hello"
print(type(z))
OUTPUT FORMATTING:
x=5;y=10
print('The value of x is {} and y is {}'.format (x,y))
CODERZ ACADEMY
print('Hello {name},{greeting}'.format (greeting='Good
morning',name='Ramesh')))
print(1,2,3,4)
print(1,2,3,4,sep='*')
print(1,3,5,7,sep='#',end='&')
CODERZ ACADEMY
OPERATORS
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
CODERZ ACADEMY
1.Arithmetic Operators
ADDITION
x=5
y=3
print(x + y)
SUBRACTION
x=5
y=3
print(x - y)
CODERZ ACADEMY
MULTIPLICATION
x=5
y=3
print(x * y)
DIVISION
x=5
y=3
print(x / y)
MODULUS
x=5
y=3
print(x % y)
EXPONENTIATION
x=2
y=5
print(x ** y) #same as 2*2*2*2*2
CODERZ ACADEMY
FLOOR DIVISION
x = 15
y=2
print(x // y)
#the floor division rounds the result down to the nearest
#whole number
2.Assignment Operators
CODERZ ACADEMY
EXAMPLE 1:
x=5
x+=3
print(x) #OUTPUT IS 8
EXAMPLE 2:
x=5
x-=3
print(x) # OUTPUT IS 2
EXAMPLE 3:
x=5
x*=3
print(x) #OUTPUT IS 15
EXAMPLE 4:
x=5
x/=3
print(x) #OUTPUT IS 1.6
CODERZ ACADEMY
EXAMPLE 5:
x=5
x%=3
print(x) #OUTPUT IS 2
EXAMPLE 6:
x=5
x//=3
print(x) #OUTPUT IS 1
EXAMPLE 7:
x=5
x**=3
print(x) #OUTPUT IS 125
CODERZ ACADEMY
3.Comparison Operators
EXAMPLE
a=5
b=3
print(a>b) #True
print(a<b) #False
print(a>=b) #False
CODERZ ACADEMY
print(a<=b) #False
print(a==b) #False
print(a!=b) #True
4.Logical Operators
CODERZ ACADEMY
and operator
x=5
print(x < 3 and x < 10) #False
or operator
x=5
print(x < 6 or x > 4) #True
not operator
x=5
print(not(x < 6 or x > 4)) #False
5.Identity Operators
Identity operators are used to compare the objects, not if
they are equal, but if they are actually the same object,
with the same memory location:
Operator Description Example
is Returns True if x is y
both variables are
the same object
is not Returns True if x is not y
both variables are
CODERZ ACADEMY
not the same
object
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
print(x is y)
print(x == y)
CODERZ ACADEMY
EXAMPLE(is not)
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is not z)
# returns False because z is the same object as x
print(x is not y)
# returns True because x is not the same object as y, even
if they have the same content
print(x != y)
# to demonstrate the difference betweeen "is not" and "!=":
this comparison returns False because x is equal to y
CODERZ ACADEMY
6.Membership Operators
CODERZ ACADEMY
EXAMPLE
IN OPERATOR
x = ["apple", "banana"]
print("banana" in x)
x = ["apple", "banana"]
print("orange" in x)
OUTPUT
False
NOT IN OPERATOR
x = ["apple", "banana"]
print("pineapple" not in x)
# returns True because a sequence with the value
"pineapple" is not in the list
CODERZ ACADEMY
Output
True
x = ["apple", "banana"]
print("apple" not in x)
output
false
7.Bitwise Operators
CODERZ ACADEMY
bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by
pushing zeros in
from the right
and let the
leftmost bits fall
off
>> Signed right shift Shift right by
pushing copies of
the leftmost bit in
from the left, and
let the rightmost
bits fall off
EXAMPLE 1:
a=2
b=6
print(a&b) # OUTPUT IS 2
EXAMPLE 2:
CODERZ ACADEMY
a=2
b=6
print(a|b) # OUTPUT IS 6
EXAMPLE 3:
a=2
b=6
print(a^b) # OUTPUT IS 4
Exercise:
CODERZ ACADEMY
and compound interest.
SI=PNR/100
CI=P(1+R/100)n
CODERZ ACADEMY
LIST
Eg1:Empty List
x=[]
Eg2:list of integers
x=[1,2,3,4]
print(x)
print(type(x))
<class list>
CODERZ ACADEMY
Eg3:
Eg4:mixed datatypes
x=[22,3.45,'a',"Siva KUMAR"]
print(x)
x=[22,33,44]
print(x[2])
Note:
seq.name index
CODERZ ACADEMY
index always starts with zero
Eg6:negative indexing
x=[22,33,44]
print(x[0])
print(x[1])
print(x[2])
print(x[-1])
print(x[-2])
print(x[-3])
Note:
-1 index denotes last element
-2 index denotes 2nd element from last
+ve index starts with 0
-ve index starts with -1
+ve index denotes elements from left to right
-ve index denotes elements from right to left
x=[22,33,44]
CODERZ ACADEMY
0 1 2
-3 -2 -1
Eg7:Slicing
x=['a','b','c','d','e']
print(x[2:4]) #elements from 2nd index to 3rd #index
print(x[:4]) #elements from 0th index to 3rd index
print(x[2:]) #elements from 2nd index to last #index
print(x[:])#all elements
print(x[1:-2]) #elements from 2nd index to 2nd element
from last
x=[22,33,44,55,66,77,88]
x[1]=11
print(x)
CODERZ ACADEMY
Allow Duplicates
Since lists are indexed, lists can have items with the same
value:
Example
Eg:9
Append Items
Eg:10
x=[1,2,3]
x.append(33)
print(x)
CODERZ ACADEMY
Extend List
Eg:11
x.extend([11,22,44])
print(x)
Insert Items
Eg:12
CODERZ ACADEMY
a = ["apple", "banana", "cherry"]
a.insert(1, "orange")
print(a)
Eg13:inserting an element
x=[1,2,3]
x.insert(1,22)
x[2:2]=[4,5,6]
print(x)
Eg14:deletion
x=[1,2,3,4,5,6,7,8,9]
del x[1]
print(x)
x.remove(9)
print(x)
CODERZ ACADEMY
Eg:15
pop
Eg:16
clear
x.clear()
print(x)
x=[1,2,3,4,2]
print(x.index(3))
print(x.count(2))
x.sort()#list is sorted
print(x)
x=[22,11,44,55,3]
print(sorted(x)) #return sorted list, doesnt sort the #list
x.reverse()
CODERZ ACADEMY
print(x)
z=[1,2,3,4]
print(2 in z)
print(2 not in z)
Eg19:all,any,len,max,min,sum methods
x=[1,2,3,4]
print(all(x)) #if all elements are non zero returns #True
print(any(x)) #if any one element is non zero #returns True
print(len(x))
print(max(x))
print(min(x))
print(sum(x))
l1=[[1,2,3],[4,5,6],[7,8,9]]
CODERZ ACADEMY
l2=[[1,2,3],[4,5,6],[7,8,9]]
l3=[]
for i in range(3):
for j in range(3):
l3.append(l1[i][j] + l2[i][j])
print(l3)
Eg21:method2:
l1=[[1,2,3],[4,5,6],[7,8,9]]
l2=[[1,2,3],[4,5,6],[7,8,9]]
l3=[[0,0,0],[0,0,0],[0,0,0]]
for i in range(3):
for j in range(3):
l3[i][j]=l1[i][j] + l2[i][j]
print(l3)
CODERZ ACADEMY
Example
>>nums=[25,12,36,95,14]
>>nums
[25,12,36,95,14]
>>nums[0]
25
>>nums[-5]
25
>>nums[4]
14
>>nums[2:]
[36,95,14]
>>nums[-1]
CODERZ ACADEMY
14
names=[“navin”,”kiran”,”john”]
>>names
[‘navin’,’kiran’,’john’]
>>values=[9.5,’Navin’,25] # enter different type of
data type & it accept
>>mil=[nums,names]
>>mil
[[25,12,36,95,14],[‘navin’,’kiran’,’john’]]
>>nums.append(45) # Add it last value
>>nums
[25,12,36,95,14,45]
>>nums.insert(2,77)
[25,12,77,38,95,14,45]
>>nums.remove(14) # delete value
>>nums
[25,12,77,36,95,45]
>>nums.pop(1) # delete value using index
value
12
>>>nums
[25,77,36,95,45]
>>nums.pop() # Without specifying
CODERZ ACADEMY
delete last element
45
>>del num[2:]
>>nums
25,77
>>nums.extend([29,12,14,36])
>>nums
[25,77,29,12,14,36]
CODERZ ACADEMY
TUPLE
Eg1:empty tuple
t=()
print(t)
type(t)
<class tuple>
Eg2:
t=(1,2,3,4)
print(t)
CODERZ ACADEMY
t=(1,2,3,"deepak")
print(t)
Eg3:indexing ,slicing
t=(1,2,3,4)
print(t[2])
print(t[2:3])
Eg4:unpacking a tuple
t=(1,2,3)
print(t)
x,y,z=t
print(x)
print(y)
print(z)
Eg5:changing elements
t=(1,2,3)
t[1]=22 #error
CODERZ ACADEMY
print(t)
Eg6:deletion
t=(1,2,3)
del t[2] #error
del t #deleted
Eg7:count,index methods
t=(1,2,3,4,2)
print(t.count(2))
print(t.index(3)) #2
len
Tuple Length
Eg8:len,max,min methods
t=(1,2,3,4,5)
CODERZ ACADEMY
print(len(t))
print(max(t))
print(min(t))
Example
Multiply Tuples
Example
CODERZ ACADEMY
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
CODERZ ACADEMY
SET
unordered collection
have unique elements
immuatable elements
elements enclosed with curly braces {}
operations:
o union,intersection,difference,...
Creation:
Method1:
s={1,2,3,4}
Eg1:set of integers
s={22,33,76,2}
print(s)
type(s)
CODERZ ACADEMY
s={22,3.3,"Arun",'A'}
print(s)
s={22,3,3}
print(s) # duplicate elements omitted
Eg4:empty set
s={}
print(type(s))
s=set() # s={} --> not an set its dictionary
print(type(s))
s={1,2,3}
print(s)
s.add(4)
print(s)
CODERZ ACADEMY
Eg6:update method: to add multiple elements
s={1,2,3}
print(s)
s.update([11,22,33])
print(s)
Eg7:discard
s={1,2,3}
print(s)
s.discard(3)
print(s)
s={1,2,3}
print(s)
print(s.pop())
print(s)
CODERZ ACADEMY
s={1,2,3}
print(s)
s.clear()
print(s)
SET Operations:
1.Union operation:
using '|'('OR') operator
using union method
S1 S2
1,2,3 4,5 6,7,8
Eg1:
s1={1,2,3,4,5} union
s2={4,5,6,7,8}
print(s1|s2)
print(s1.union(s2))
2.Intersection Operation:
CODERZ ACADEMY
Eg2: S1 S2
1,2,3 4,5 6,7,8
s1={1,2,3,4,5}
s2={4,5,6,7,8}
print(s1&s2)
intersection
print(s1.intersection(s2))
3.Difference Operation:
Eg3:
S1 S2
1,2,3 4,5 6,7,8
s1={1,2,3,4,5}
s2={4,5,6,7,8}
print(s1-s2) S1-S2
print(s1.difference(s2)) S1 S2
print(s2-s1) 1,2,3 4,5 6,7,8
print(s2.difference(s1)
CODERZ ACADEMY
4.Symmetric Difference Operation:
S2-S1
Eg4:
s1={1,2,3,4,5}
s2={4,5,6,7,8}
print(s1^s2)
print(s1.symmetric_difference(s2))
s={1,2,3,4}
print( 1 in s)
print( 1 not in s)
print( 11 not in s)
Eg6:max,min,sum method
s={1,2,7,3,4}
print("MAX:", max(s))
CODERZ ACADEMY
print("MIN:" ,min(s))
print("SUM:", sum(s))
print("Any true value: ", any(s))
print("All true values: ", all(s))
print("Sorted: ", sorted(s))
print("Length:" , len(s))
Eg7:vowels counting
s={'p','y','t','h','o','n','l','e','a','r','n'}
c=0
for a in s:
if a in {'a','e','i','o','u'}:
c=c+1
print("No of vowels:" ,c)
CODERZ ACADEMY
DICTIONARY
Eg1:Empty dict
d={}
print(d)
print(type(d))
Eg2:integer keys
d={1:'one',2:'two'}
print(d)
CODERZ ACADEMY
Eg3:mixed keys
d={'num':201,'name':'kavin',1:'semester'}
print(d)
d=dict({1:'one',2:'two'})
print(d)
eg5:access elements
d={'num':201,'name':'kavin',1:'semester'}
print(d['num'])
print(d['name'])
print(d[1])
Eg6:change value
CODERZ ACADEMY
d={'num':201,'name':'kavin',1:'semester'}
d['num']=303
print(d)
Eg7:add elements
d={'num':201,'name':'kavin',1:'semester'}
d['mark']=88
print(d)
Eg8:pop() method
d={'num':201,'name':'kavin',1:'semester'}
print(d.pop(1))
print(d)
Eg9:popitem() method
- to remove last item
d={'num':201,'name':'kavin',1:'semester'}
CODERZ ACADEMY
print(d.popitem())
print(d)
Eg10:del
d={'num':201,'name':'kavin',1:'semester'}
del d['num']
print(d)
Eg11:clear
d={'num':201,'name':'kavin',1:'semester'}
d.clear()
print(d)
d={'num':201,'name':'kavin',1:'semester'}
del d
print(d)
d={'num':201,'name':'kavin','semester':2}
for i in d.items():
CODERZ ACADEMY
print(i)
x=list(sorted(d.keys()))
print(x)
Method1:
d={}
for x in {1,2,3}:
d[x]=x
print(d)
method2:
d={ }
for x in range(10):
d[x]=x
print(d)
method3:
CODERZ ACADEMY
print(d)
d={'num':201,'name':'kavin','semester',2}
print('num' in d)
Eg18:iteration
d={'num':201,'name':'kavin','semester':2}
for i in d:
CODERZ ACADEMY
print(d[i])
Eg19:has_key,len,sorted,values,items methods
d={'num':201,'name':'kavin','semester':2}
print(len(d))
print(sorted(d))
print(d.keys())
print(d.values())
print(d.items())
Eg20:updation
d1={1:11,2:22}
d2={3:33,4:44}
d2.update(d1)
print(d2)
More Examples:
>>>data={1:’navin’,2:’kiran’,3:’harsh’}
CODERZ ACADEMY
>>>data
{1:’navin’,2:’kiran’,3:’harsh’}
>>>data[3]
‘harsh’
>>>print(data.get(4))
None
>>>data.get(4,’not found’)
‘not found’
>>>data.get(1,’not found’)
‘navin’
>>>keys=[‘navin’,’kiran’,’harsh’]
>>>value=[‘python’,’Java’,’Js’]
CODERZ ACADEMY
>>>data=dict(zip(keys,value))
>>>data
{‘navin’:’python’,’kiran’:’Java’,’harsh’:’Js’}
>>>data[‘monika’]=’cs’
>>>data
{‘navin’:’python’,’kiran’:’Java’,’harsh’:’Js’,’monika’:’cs’}
Delete data
>>>del data[‘harsh’]
>>>data
{‘navin’:’python’,’kiran’:’Java’,’monika’:’cs’}
>>>prog={‘Js’:’Atom’,’Cs’:’VS’,’python’:[‘pychram’,’sublime’],’j
CODERZ ACADEMY
ava’:{‘JSE’:’Netbeans’,’Jee’:’Eclipse’}}
>>>prog[‘js’]
‘Atom’
>>>prog[‘python’]
[‘pychram’,sublime’]
>>>prog[‘python][1]
‘sublime’
>>>prog[‘Java’]
{‘JSE’:’Netbeans’,’Jee’:’Eclipse’}
>>>prog[‘Java’][‘JEE’]
‘Eclipse’
CODERZ ACADEMY
CONDITIONAL STATEMENT
Simple if:
Syntax:
if test expression:
Statement(S)
if the text expression is false,the statement (S) is not
executed.
CODERZ ACADEMY
Exercise: Write a program to check the given number is
positive, negative or zero without else part.
If else statement:
Syntax:
if test expression:
Body of if statement
else:
Body of else statement
CODERZ ACADEMY
EXERCISE:
Write a program to check if the number is positive or
negative.
if….elif….else
syntax:
if test expression:
Body of if statement(S)
elif test expression:
Body of elif statement(S)
else:
Body of else statement(S)
elifshort of else if
CODERZ ACADEMY
print(“greatest is a”)
elif b>c:
print(“greatest is b”)
else:
print(“greatest is c”)
Exercise:
Program to input day of week in number (1…7) and print
its character equivalent.
Nested if statement :
We can have a if...elif...else statement inside
another if..elif..else statement. This is called nesting in
computer programming.
Example:
num=float(input(“enter a no:”))
if num>=0:
if num==0:
print(“zero”)
else:
print(“positive number”)
CODERZ ACADEMY
else:
print(“negative number”)
Example 2:
Program to find the greater of three number.
a=20
b=30
c=15
if a>b:
if a>c:
res=a
else:
res=c
elif b>c:
res=b
else:
res=c
print(“greatest value=”,res)
CODERZ ACADEMY
Exercise: write a python program-
(1) to find given year is leap year or not.
(2) to find second maximum of three number.
(3) to input three subject mark and check all are above 40
or using nested if.
If all are above 40 – its eligible.
If any one is below 40 – its not eligible.
(4) to input months value between 1…12 and find the
month fall in which quarter.
CODERZ ACADEMY
print(“2nd largest is:”,c)
else:
print(“2nd largest :”,a)
elif a>b:
print(“2nd largest is:”,a)
else:
print(“2nd largest is:”,b)
CODERZ ACADEMY
LOOPING STATEMENTS
syntax:
for var in sequence:
body of for loop statement.
var - variable that takes the value of the item inside the
sequence on each iteration.
Program1:
for i in “coderz”:
print(i)
output:
c
o
CODERZ ACADEMY
d
e
r
z
Advantage:
This function does not solve all the value in memory,
it would be inefficient. so it remember the start,stop,step
size and generate the next number on the go.
CODERZ ACADEMY
o/p:
5
10
:
45
Exercise:
1. program to sum the even number 2…n.
2. program to calculate the average of number in a given
list.
3. program to find given number is a perfect number or
not.
digits=[1,2,3,4,5]
for i in digits:
print(i)
else:
print (“no items left”)
o/p:
CODERZ ACADEMY
1
2
3
4
5
no items left
CODERZ ACADEMY
program to add natural number 1+2+3+…..+n
n=int(input(“enter a number:”))
sum=0
i=1
while i<=n:
sum=sum+i
i=i+1
print (“the sum is”,sum)
i=1
while i<=3:
print (“\n inside loop”)
i=i+1
else:
print(“\n finally print while cond is false”)
CODERZ ACADEMY
Exercise:write a python program
break statement:
for val in “string”:
if val==”i”:
break
print(val)
print(“the end”)
CODERZ ACADEMY
o/p:
s
t
r
the end
continue statement:
for val in “string”:
if val ==”i”:
continue
print(val)
print(“the end”)
o/p:
s
t
r
n
g
the end
CODERZ ACADEMY
pass statement:
syntax:pass
CODERZ ACADEMY
FUNCTIONS
SYNTAX:
def func_name(parameters):
”””doc string”””
statements
def Keyword
: end of function header
Example:
def welcome_func(name): #func definition
print(“Hello,” + name + “Good morning!”)
CODERZ ACADEMY
The Return Statement:
SYNTAX:
return [expression_list]
n=int(input(“Enter a number:”))
res= sample(n) #function calling
print(“The square of %d is %d”%(n,res))
CODERZ ACADEMY
x=x*i
return x
m= input(“Enter a number…”)
print(“factorial value ={}”.format(fact(int(m))))
FUNCTIONS ARGUMENTS:
def welcome_func(name,msg):
print(“Hello”, name + ‘,’ + msg)
welcome_func(“priya”,”good morning”)
OUTPUT:
CODERZ ACADEMY
VARIABLE FUNCTION ARGUMENTS:
welcome_func(“kumaresan”)
welcome_func(“Prakash”,”have a nice day”)
def welcome_func(name,msg):
print(“hai”,name,msg)
name=”karthick”
welcome_func(name=”karthick”,msg=”Have a nice day”)
welcome_func(msg=”have a nice day”, name=”karthick”)
welcome_func(name,msg= “have a nice day”)
CODERZ ACADEMY
name,msg Keyword
Example1:
def arb_func(*names):
for na in names:
print(“hello”,na)
arb_func(“Priyadarshini”,”radika”,”Jayaraman”,”harsh”)
CODERZ ACADEMY
Example2:
def sample_func(*num):
for i in num:
print(i)
print(type(i))
sample_func(10,20)
sample_func(“Raj”,”Kumar’)
sample_func(70,”jayaraman”)
4. **KWARGS IN PYTHON:
def test_variable(sstar,**dstar):
print(“formal arguments:”,sstar)
for v in dstar:
print(“another keyword arg: %s is %s”%(v,dstar[v]))
CODERZ ACADEMY
5.PYTHON RECURSION:
python program using recursive to find prime or not
def check(n,div=None):
if div is None:
div=n-1
while div>=2:
if n%div==0:
print(“not a prime number”)
return False
else:
return check(n,div-1)
else:
print(“no is prime”)
return True
n=int(input(“enter number:”))
check(n)
CODERZ ACADEMY
6.PYTHON LAMBDA FUNCTION:
In Python , anonymous function is a function that is
defined without name is called as lambda function.
It is also called as anonymous function.
syntax:
lambda arguments:expression
CODERZ ACADEMY
Example2:
same as above
def sumtwo(x,y):
return(x+y)
print (“addition of two value is:”,sumtwo(5,1))
Exercise:
1.write a program for SI and CI using functions
3.write a recursive program to find factorial of number.
4.write a recursive program to find sum of n number.
5.write a program power of 2 using anonymous function
CODERZ ACADEMY
BUILT IN STRING MANIPULATION
Capitalize
Program-1
'i love india'.capitalize()
isalnum
Returns true if the characters in the string <str> are
alphanumeric (alphabets or numbers) and there is at least
one characters ,otherwise false.
Program-2
s="abcd123"
s.isalnum()
True
isalpha
returns true if all characters in the string <str>are
alphabetic and there is at least one character ,otherwise
false.
program-3
s1='hello'
CODERZ ACADEMY
s1.isalpha()
True
s2='hello1'
s2.isalpha()
False
isdigit
returns true if all the characters in the string <str> are
digits
program-4
s3='123'
s3.isdigit()
True
s3='123n'
s3.isdigit()
False
Isspace()
Returns true if there are only whitespace characters in the
string <str> .there must be at least one character.
CODERZ ACADEMY
Program-5
s1=" "
s1.isspace()
True
Isupper
Program-6
a='coderz'
a.isupper()
False
Islower
Program-7
a='CODERZ'
a.islower()
False
a.isupper()
True
Istitle
Program-8
The istitle() method returns True if all words in a text start
CODERZ ACADEMY
with a upper case letter, and the rest of the word are lower
case letters, otherwise False.
Example:
"To Be Or Not To Be".istitle()
True
center() Method
txt = "banana"
x = txt.center(20)
print(x)
find() Method
replace() Method
CODERZ ACADEMY
x = txt.replace("bananas", "apples")
print(x)
title() Method
upper() Method
startswith() Method
Return True if the object value is start with the value which
is mentioned within startwith().
CODERZ ACADEMY
join() Method
swapcase()
"Hello World".swapcase()
'hELLO wORLD'
CODERZ ACADEMY
map(),filter(),reduce()
nums=[3,2,6,8,4,6,9,7]
evens=list(filter(lambda n: n%2==0,nums))
print(evens)
doubles=list(map(lambda n:n*2,evens))
print(doubles)
sum=reduce(lambda a,b:a+b,doubles)
print(sum)
DECORATOR
Decorators allows programmers to modify the behavior
of a function or class.
It will add extra features into existing function at
compile time itself.
Example:
def div(a,b):
print(a/b)
def smart_div(func):
CODERZ ACADEMY
def inner(a,b):
if a<b:
a,b=b,a
return func(a,b)
return inner
div=smart_div(div)
div(2,4)
abs() Function
abs(-10)
10
all() Function
CODERZ ACADEMY
s=[0,1,2]
all(s)
False
s=[]
all(s)
True
>>> x=10
>>> bin(x)
'0b1010'
bool() Function
CODERZ ACADEMY
object is empty, like [], (), {} The object is False. The object
is 0.
x = bool(1)
print(x)
chr() Function
x = chr(97)
print(x)
filter() Function
CODERZ ACADEMY
ages = [5, 12, 17, 18, 24, 32]
def myFunc(x):
if x < 18:
return False
else:
return True
for x in adults:
print(x)
id() Function
>>> x=45
>>> id(x)
1695601816
CODERZ ACADEMY
len() Function
max() Function
x = max(5, 10)
print(x)
min() Function
x = min(5, 10)
print(x)
ord() Function
x = ord("h")
print(x)
CODERZ ACADEMY
pow() Function
x = pow(4, 3)
print(x)
round() Function
x = round(5.76543, 2)
print(x)
sum() Function
a = (1, 2, 3, 4, 5)
x = sum(a)
print(x)
CODERZ ACADEMY
MODULES:
calculator
CODERZ ACADEMY
Eg:3
platform.processor()
Eg:4
from platform import *
Eg:5
processor()
Eg:6
from platform import os,processor,machine
Eg:7
os
processor()
machine()
Eg:8
import platform as p
p.processor()
def add(x,y):
return x+y
def sub(x,y):
CODERZ ACADEMY
return x-y
def mul(x,y):
return x*y
def div(x,y):
return x/y
Another file:
import arith
print(arith.add(22,33))
print(arith.sub(22,33))
print(arith.mul(22,33))
print(arith.div(22,33))
PREDEFINED MODULE:
Decimal Module:
to handle decimal numbers
Eg:
import decimal
>>> print(decimal.Decimal(0.5))
0.5
CODERZ ACADEMY
>>> print(decimal.Decimal(0.1))
0.100000000000000005551115123125782702118158340
45410
Eg:2
>>> from decimal import Decimal as D
>>> print(D(1.2)+D(2.2))
3.400000000000000133226762955
Fraction Module:
Eg:1
import fractions
print(fractions.Fraction(1.5))
print(fractions.Fraction(5))
print(fractions.Fraction(1,3))
math module:
Eg:1
import math
print("PI:", math.pi)
Eg:2
import math as m #import with renaming
print("PI:", m.pi)
CODERZ ACADEMY
Eg3:
We can import specific name from a module without
importing the whole module.
from math import pi
print(“The value of pi is”,pi)
Eg:4
import math
print(math.cos(math.pi))
print(math.exp(10))
print(math.log10(1000))
print(math.factorial(6))
random module:
Eg:1
import random
print(random.randrange(10,20))
x=['a','b','c','d']
print(random.choice(x))
random.shuffle(x)
print(x)
print(random.random())
CODERZ ACADEMY
Class & object
Python is an object oriented programming
language.
collection of variables & methods(function)
Create a Class
class demo:
pass
Eg:2
Accessing members
class sample:
x,y=10,20
s=sample()
print("value of x",s.x)
CODERZ ACADEMY
print("value of y",s.y)
print("value of ",s.x+s.y)
Eg:3
class add:
def get(self):
self.a=int(input("enter a number"))
self.b=int(input("enter a number"))
def cals(self):
self.c=self.a+self.b
def show(self):
print("Add:" , self.c)
a1=add()
a1.get()
a1.cals()
a1.show()
Eg:3
class std:
m1,m2,m3=98,97,100
def process(self):
self.sum=self.m1+self.m2+self.m3
CODERZ ACADEMY
self.avg=sum/3
print(self.sum)
print(self.avg)
s=std()
s.process()
Eg:4
class vehicle:
name="BMW"
kind="CAR"
color="white"
value=100.00
def description(self):
car="%s is a %s %s worth
$%.2f."%(self.name,self.color,self.kind,self.value)
return car
car1=vehicle()
print(car1.description())
CODERZ ACADEMY
Constructor
Eg:1
class person:
def __init__(self, name):
self.name = name
def say_hi(self):
print('Hello, my name is', self.name)
p = person('santhosh')
p.say_hi()
Eg:2
class add:
def __init__(self,x=10,y=10):
self.a=x
self.b=y
def cals(self):
self.c=self.a+self.b
def show(self):
print("Add:" , self.c)
a1=add()
a1.cals()
CODERZ ACADEMY
a1.show()
a2=add(22)
a2.cals()
a2.show()
a3=add(22,33)
a3.cals()
a3.show()
Eg:3
class employee:
def __init__(self,name,id):
self.id=id
self.name=name
def display(self):
print("Id:%d \nname:%s"%(self.id,self.name))
emp1=employee("john",101)
emp2=employee("david",102)
emp1.display()
emp2.display()
CODERZ ACADEMY
Eg:4
Default constructor
class std:
roll=101
name="thilo"
def __init__(self):
print(self.roll,self.name)
st=std()
to delete object
Eg:1
class example:
def __init__(self):
print("object created")
def __del__(self):
print("object destroyed")
a=example()
del a
CODERZ ACADEMY
Eg:2
class add:
def get(self):
self.a=int(input("enter a number"))
self.b=int(input("enter a number"))
def cals(self):
self.c=self.a+self.b
def show(self):
print("Add:" , self.c)
a1=add()
a1.get()
a1.cals()
a1.show()
del a1
a1.show() #error
CODERZ ACADEMY
Built In Class Function
getattr(obj,name,default)
It is used to access the attribute of the object.
setattr(obj,name,value)
It is used to set a particular value to the specific
attribute of an object.
delattr(obj,name)
Delete the specific attribute.
hasattr(obj,name)
It returns true if the object contains some specific
attribute.
Eg:1
class student:
def __init__(self,name,id,age):
self.name=name
self.age=age
self.id=id
CODERZ ACADEMY
s=student("raj",101,25)
print(getattr(s,"name"))
setattr(s,"age",27)
print(getattr(s,"age"))
print(hasattr(s,"id"))
delattr(s,"age")
print(s.age)
CODERZ ACADEMY
INHERITANCE
Single Inheritance:
Class1
Class2
CODERZ ACADEMY
Eg:14 Single Inheritance:
class person:
def __init__(self,no,name):
self.empno=no
self.ename=name
def dispdata(self):
print("employee no:",self.empno)
print("employee name:",self.ename)
class employee(person):
def callme(self):
print("i can use the attribute of person")
per=person(101,"ramkumar")
emp=employee(102,"suresh")
print("employee details")
print("_"*25)
per.dispdata()
emp.dispdata()
CODERZ ACADEMY
Multilevel Inheritance:
Class1
Class2
Class3
class addition:
def gets(self):
self.a=int(input("Enter a Number: "))
self.b=int(input("Enter a Number: "))
def calladd(self):
self.c=self.a+self.b
def disadd(self):
print("Add: ",self.c)
class subtraction(addition):
def callsub(self):
CODERZ ACADEMY
self.d=self.a-self.b
def dissub(self):
print("Sub: ",self.d)
class multiplication(subtraction):
def callmul(self):
self.e=self.a*self.b
def dismul(self):
print("Mul: ",self.e)
a1=multiplication()
a1.gets()
a1.calladd()
a1.disadd()
a1.callsub()
a1.dissub()
a1.callmul()
a1.dismul()
CODERZ ACADEMY
Hierarchical Inheritance:
Class1
Class2 Class3
class addition:
def gets(self):
self.a=int(input("Enter a Number: "))
self.b=int(input("Enter a Number: "))
def calladd(self):
self.c=self.a+self.b
def disadd(self):
print("Add: ",self.c)
class subtraction(addition):
def callsub(self):
CODERZ ACADEMY
self.d=self.a-self.b
def dissub(self):
print("Sub: ",self.d)
class multiplication(addition):
def callmul(self):
self.e=self.a*self.b
def dismul(self):
print("Mul: ",self.e)
a1=subtraction()
a1.gets()
a1.calladd()
a1.disadd()
a1.callsub()
a1.dissub()
a2=multiplication()
a2.gets()
a2.calladd()
a2.disadd()
a2.callmul()
a2.dismul()
CODERZ ACADEMY
Hybrid Inheritance:
Class2 Class3
Class3
class addition:
def gets(self):
self.a=int(input("Enter a Number: "))
self.b=int(input("Enter a Number: "))
def calladd(self):
self.c=self.a+self.b
def disadd(self):
print("Add: ",self.c)
class subtraction(addition):
def callsub(self):
CODERZ ACADEMY
self.d=self.a-self.b
def dissub(self):
print("Sub: ",self.d)
class multiplication(addition):
def callmul(self):
self.e=self.a*self.b
def dismul(self):
print("Mul: ",self.e)
class division(subtraction,multiplication):
def calldiv(self):
self.f=self.a//self.b
def disdiv(self):
print("Div: ",self.f)
a1=division()
a1.gets()
a1.calladd()
a1.disadd()
CODERZ ACADEMY
a1.callsub()
a1.dissub()
a1.callmul()
a1.dismul()
a1.calldiv()
a1.disdiv()
Multiple Inheritance:
Class1 Class2
Class3
CODERZ ACADEMY
class student:
tot=0;avg=0.0;res=” “
def __init__(self,no,na):
self.stdno=no;self.stdname=na
def stdfun(self):
print(“student no:”,self.stdno,”\nstudent
name:”,self.stdname)
class test1:
def __init__(self,m1,m2):
self.p1=m1;self.p2=m2
def markdisp1(self):
print(“c language:”,self.p1)
print(“c++ language:”,self.p2)
class test2:
def __init__(self,m3,m4)
self.p3=m3;self.p4=m4
def markdisp2(self):
print(“java:”,self.p3)
print(“python:”,self.p4)
CODERZ ACADEMY
class result(student,test1,test2):
def __init__(self,no,na,m1,m2,m3,m4):
student.__init__(self,no,na)
test1.__init__(self,m1,m2)
test2.__init__(self,m3,m4)
def calfun(self):
self.tot=self.p1+self.p2+self.p3+self.4
self.avg=self.tot/4
if self.p1>=40 and self.p2>=40 and self.p3>=40
and self.p4>=40:
self.res=”pass”
else:
self.res=”fail”
def resdisplay(self):
print(“total:”,self.tot)
print(“average:”,self.avg)
print(“result:”,self.res)
ob=result(101,”raj”,67,78,89,90)
ob.calfun()
print(“_”*25)
CODERZ ACADEMY
ob.stdfun()
print(“_”*25)
ob.markdisp1()
ob.markdisp2()
print(“_”*25)
ob.resdisplay()
print(“_”*25)
Exercise 1:
Output:
Total seating capacity =50
Final fare amount =5500
CODERZ ACADEMY
2.student (parent) --- > name,age ,gender
Test(child 1) ---- > get five sub marks
mark (child2) ----- > display Nam,e age ,gender and
total sub mark
Exercise: 2
CODERZ ACADEMY
a) Accept deposit from a customer and update the
balance
b) Display the balance
c) Permit withdrawal and update the balance
EXCEPTION HANDLING
The try block lets you test a block of code for Errors.
Program-1
print(x)
c=2+3
print(c)
CODERZ ACADEMY
Solution:
try:
print(x)
except:
print("error occur")
finally:
c=2+3
print(c)
Index Error
m=[1,2,3]
m[4]
CODERZ ACADEMY
Name Error:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Finally
CODERZ ACADEMY
program-1
a=int(input("enter a number"))
b=int(input("enter a number"))
try:
c=a//b
print("c:",c)
except ZeroDivisionError:
print("Cant divide a number with Zero")
print("END")
program-2
try:
a,b=eval(input("Enter two numbers sep. by camma"))
c=a+b
print("C:",c)
except SyntaxError:
print("Numbers must be seperated by comma")
CODERZ ACADEMY
print("This is the line")
program-3
try:
a,b=eval(input("enter 2 nos seperated by comma: "))
c=a//b
print("c:",c)
except ZeroDivisionError:
print("Cant divide a number with Zero")
except SyntaxError:
print("Comma is missing in input values")
CODERZ ACADEMY
print("Comma is missing in input values")
except:
print("Wrong Input")
else:
print("No Error")
finally:
print("Code Executed successfully")
CODERZ ACADEMY
print("Voting age validation Finished")
program-2
class NegativeValueError(Exception):
pass
class ZeroValueError(Exception):
pass
while True:
try:
n=int(input("Enter a number: "))
if n==0:
raise ZeroValueError
if n<0:
raise NegativeValueError
else:
print("Valid Input")
print("The entered number is ", n)
break;
except NegativeValueError:
print("Number should not be negative")
CODERZ ACADEMY
except ZeroValueError:
print("Number should not be Zero")
Module Package:
import math
num=int(input("please enter the number to calculate
factorial of:"))
try:
result=math.factorial(num)
print(result)
except:
print("negative number")
Exception keyword
try:
print(a)
except Exception as e:
print(e)
CODERZ ACADEMY
FILE HANDLING
Syntax:
Open syntax:
var_name=open(“file name”,mode)
Close syntax:
var_name=close()
Program-1
f=open("wel.txt",'w')
f.close()
CODERZ ACADEMY
Example:
f=open("wel.txt",'w')
f.write("first line")
f.close()
Example:
Print one line statement
f=open("wel.txt",'w')
a=input(“enter a string:”)
f.write(a)
f.close()
Example:
Print multi line statement
f=open("wel.txt",'w')
for i in range(3):
a=input(“Enter a sring:”)
f.write(a)
f.close()
CODERZ ACADEMY
program2:
Read file
f = open("wel.txt", "r")
print(f.read())
Program-3
f = open("wel.txt", "r")
print(f.read(5))
Read Lines
CODERZ ACADEMY
Program-4
f = open("wel.txt", "r")
print(f.readline())
Program-5
f = open("wel.txt", "r")
print(f.readline())
print(f.readline())
for loop
By looping through the lines of the file, you can
read the whole file, line by line
Program-6
f = open("wel.txt", "r")
for x in f:
print(x)
Delete a File
CODERZ ACADEMY
To delete a file, you must import the OS module, and run
its os.remove() function:
import os
os.remove("wel.txt")
PICKLE MODULE
CODERZ ACADEMY
read binary
import pickle
file="aaa.txt"
fileobject=open(file,"rb")
print(pickle.load(fileobject))
fileobject.close()
METHOD OVERLOADING
CODERZ ACADEMY
Program-1
Error program
Passing one arguement
class sample:
def second(self,a,b):
c=a+b
return c
a=sample()
print(a.second(10))
program-2
how to clear this error:
class demo:
def sum(self,a=None,b=None,c=None):
if a!=None and b!=None and c!=None:
c=a+b+c
elif a!=None and b!=None:
c=a+b
else:
c=a
print(c)
obj=demo()
CODERZ ACADEMY
obj.sum(10,20,30)
obj.sum(10,20)
obj.sum(10)
METHOD OVERRIDING
Program-1
class father:
def show(self):
print("i am father")
class son(father):
pass
CODERZ ACADEMY
a=son()
a.show()
program-2
class father:
def show(self):
print("i am father")
class son(father):
def show(self):
print("i am son")
a=son()
a.show()
CODERZ ACADEMY
OPERATOR OVERLOADING
Program-1
a=20
b=10
print(a+b)
program-2
a=10
b=20
print(int.__add__(a,b))
(or)
a=10
CODERZ ACADEMY
b=20
print(int.__sub__(a,b))
(or)
a=10
b=20
print(int.__mul__(a,b))
(or)
a=10
b=20
print(int.__truediv__(a,b))
program-3
class student:
def __init__(self,m1,m2):
self.m1=m1
self.m2=m2
print(m1+m2)
def __add__(self,others):
CODERZ ACADEMY
m1=self.m1+others.m1
m2=self.m2+others.m2
s3=student(m1,m2)
s1=student(10,20)
s2=student(20,30)
s3=s1+s2
program-3
class book:
def __init__(self,price):
self.price=price
b1=book(10)
b2=book(20)
b3=b1.price+b2.price
print(b3)
CODERZ ACADEMY
program-4
class book:
def __init__(self,price):
self.price=price
def __add__(self,other):
return self.price+other.price
b1=book(10)
b2=book(20)
b3=b1+b2
print(b3)
__sub__()
__mul__()
__pow__()
__truediv__()
__floordiv__()
__mod__()
CODERZ ACADEMY
POLYMORPHISM
Program-1
class version1:
def button(self):
print("colour red")
class version2(version1):
def button(self):
print("colour yellow")
a=version2()
a.button()
CODERZ ACADEMY
program-3
class India:
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the most widely spoken language of
India.")
def type(self):
print("India is a developing country.")
class USA:
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
CODERZ ACADEMY
print("USA is a developed country.")
obj_ind = India()
obj_usa = USA()
obj_ind.capital()
obj_ind.language()
obj_ind.type()
(or)
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()
CODERZ ACADEMY
MULTITHREADING
Program-1
class hello:
def run(self):
for i in range(5):
print("hello")
class hai:
def run(self):
for i in range(5):
print("hai")
t1=hello()
t2=hai()
t1.run()
t2.run()
CODERZ ACADEMY
Program-2
program-3
time setting
CODERZ ACADEMY
print("hello")
sleep(1)
class hai(Thread):
def run(self):
for i in range(5):
print("hai")
sleep(1)
t1=hello()
t2=hai()
t1.start()
#after start() method thread
#convert as three thread main thread ,
#thread1 and thread2
sleep(0.2)
t2.start() # run under thread 2
t1.join()
t2.join()
CODERZ ACADEMY
DATE TIME MODULE
Program-1
import datetime
x=datetime.datetime.now()
print(x)
program-2
import datetime
amPm=str(input("am or pm"))
if (amPm=="pm"):
alarmHour=alarmHour+12
while(1==1):
if(alarmHour==datetime.datetime.now().hour and
CODERZ ACADEMY
alarmMinute==datetime.datetime.now().minute):
print("wake up lazy")
break
print("existed")
CODERZ ACADEMY
from abc import ABC, abstractmethod
class polygon(ABC):
@abstractmethod #decorator
def noofsides(self):
pass
class triangle(polygon):
# overriding abstract method
def noofsides(self):
print("i have 3 sides")
class pentagon(polygon):
class hexagon(polygon):
# overriding abstract method
def noofsides(self):
print("i have 6 sides")
CODERZ ACADEMY
class quadrilateral(polygon):
# overriding abstract method
def noofsides(self):
print("i have 4 sides")
r = triangle()
r.noofsides()
k = quadrilateral()
k.noofsides()
r = pentagon()
r.noofsides()
k = hexagon()
k.noofsides()
CODERZ ACADEMY
DUCK TYPING
Duck typing is a trem commonly related to dynamically
typed programming language and polymorphism.
“If it look like duck and quacks like duck ,it’s a duck”
class pycharm:
def execute(self):
print(“compling”)
print(“running”)
class idle:
def execute(self):
print(“spell check”)
print(“convention check”)
class laptop:
def code (self,ide):
ide.execute()
ide=idle() #ide=pycharm()
CODERZ ACADEMY
lap=laptop()
lap.code(ide)
SEARCHING ALGORITHM
Linear Search:
pos=1 #Global variable
def search(list,n):
i=0
while i<len(list):
if list[i]==n:
global()[‘pos’]=i
return True
i=i+1
return False
list=[5,8,4,6,9,2]
n=9
if search(list,n):
print(“Found at”,pos+1)
else:
CODERZ ACADEMY
print(“Not Found”)
Binary Search:
pos=-1
def search(list,n):
l=0
u=len(list)-1
while l<=u:
mid=(l+u) //2
if list [mid]==n:
globals()[‘pos’]=mid
return True
CODERZ ACADEMY
else:
if list[mid]<n:
l=mid+1
else:
u=mid-1
return False
list=[4,7,8,12,45,99]
n=45
if search(list,n):
print(“Found at”,pos+1)
else:
print(“Not found”)
Bubble Sort:
def sort (nums):
for i in range (len(nums)-1,0,-1):
for j in range(i):
if num[j]>num[j+1]:
temp=nums[j]
nums[j]=nums[j+1]
nums[j+1]=temp
CODERZ ACADEMY
nums=[5,3,8,6,7,2]
sort(nums)
print(nums)
Selection Sort:
nums=[5,3,8,6,7,2]
sort(nums)
CODERZ ACADEMY
MySql Connectivity
import mysql.connector
connection=mysql.connector.connect(host=”localhost”,user
=”root”,password=”1234”,database=”coderz”)
cursor=connection.cursor()
insert1=”insert into student(roll,name)values(101,’raj’);”
cursor.execute(insert1)
connection.commit()
connection.close()
CODERZ ACADEMY
Retrive data from MySql:
import mysql.connector
connection=mysql.connector.connect(host=”local
host”,user=”root”,password=”1234”,database=”coderz”)
cursor=connection.cursor()
retrieve=”select*from coderz;”
cursor.execute(retrive)
rows=cursor.fetchall()
for row in rows:
print(row)
connection.commit()
connection.close()
import mysql.conncetor
connection=mysql.connector.connect(host=”local
host”,user=”root”,password=”1234”,database=”coderz”)
cursor=connection.cursor()
updatesql=”update student set name=’raj’where roll=’104’;”
cursor.execute(updatesql)
CODERZ ACADEMY
retrieve=”select*from student;”
cursor.execute(retrive)
rows=cursor.fetchall()
for row in rows:
print(row)
connection.commit()
connection.close()
import mysql.connector
connection=mysql.connector.connect(host=”local
host”,user=”root”,password=”1234”,database=”coderz”)
cursor=connection.cursor()
deletesql=”delete freom student where roll=’10’;”
cursor.execute(deletesql)
retrieve=”select*from student;”
cursor.execute(retrive)
rows=cursor.fetchall()
for row in rows:
print(row)
connection..commit()
connection.close()
CODERZ ACADEMY
Tkinter
What is GUI?
GUI is a desktop app which helps you to interact
with computers.
GUI
CODERZ ACADEMY
Great the GUI application main window
Add widgets
Enter the main event loop.(it will tell close window only by
manually)
import tkinter
from tkinter import *
window=tkinter.Tk()
#to rename the title of the window
window . title(“GUI”)
#pack is used to show the object in the window.
label=tkinter.Label(window,text=”Hello World”).pack()
window.mainloop()
Tkinter Widget
CODERZ ACADEMY
that displays information or provide a specific way for a user
to interact with the OS or an application.
Label
Button
Entry
Radio
Checkbox
Combo box
Scrolled text
Spin box
Menu Bar
Note book
1. Label:
Label:You can set the label font so you can make it bigger
and may be bold.
CODERZ ACADEMY
l1.grid(column=0,row=0)
window.mainloop()
l1=label(window,text=”Helloworld”font=(“Arial bold”,50))
window.geometry(‘350*200’)
l1.grid(column=0,row=0)
2. Button widgets:
Lets start by adding the button to the
bt=Button(window,text=”Enter”)
bt.grid(column=1,row=0)
CODERZ ACADEMY
bt=button(window,text=”Enter”,bg=”Orange”,fg=”red”)
bt.grid(column=1,row=0)
def clicked()
l1.configure(text=”Button was clicked!!”)
bt=Button(Window,text=”Enter”,command=clicked)
CODERZ ACADEMY
window.mainloop()
import tkinter as tk
from tkinter import.ttk
ttk.window=tk()
combo=combobox(Window)
combo[‘values’]=(1,2,3,4,5,”Text”)
#Adding the combobox items using tuple
combo.current(3)
combo.grid(column=0,row=0)
window.mainloop()
Chk_state=Boolean var()
Chk_state.set(true)
CODERZ ACADEMY
chk=checkbutton(window,text=‘select’,var=chk-state)
#passing the chk state to check button class to set the
check state.
chk.grid(column=0,row=0)
chk.pack()
window.mainloop()
Scrolled Text:
imported tkinter as tk
CODERZ ACADEMY
from tkinter import ttk
from tkinter import scrolled text
window=tk.TK()
txt=scrolled text.Scrolled
text(Window,wrap=tk.WORD,width=40,height=10)
txt.grid(column=0,pady=10,padx=10)
txt.focus() #blink cursor position
txt.insert(INSERT,’you text goes here’)
window.mainloop()
Message Box:
Shows a message box when the user clicks a
button.
show warning
show error
ask question
ask ok cancel
CODERZ ACADEMY
ask yes no
ask retry cancel
CODERZ ACADEMY
2. pack()=It organize the widget in the block,which mean it
occupies the entire available widget.
3. place()-Its used to place he widgets at a specific position
you want.
import tkinter
Window=tkinter.Tk()
window.title(“title”)
# Creating 2 frame TOP & BOTTOM
Top_frame=tkinter.frame(window).pack()
bottomframe=tkinter.frame(window).pack(side=”bottom”)
btn1=tkinter.Buttom(top_frame,text=”Button1”,fg=”red”).pa
ck()
btn2=tkinter.Buttom(top_frame,text=”Button2”,fg=”green”).
CODERZ ACADEMY
pack()
btn3=tkinter.Buttom(bottom_frame,text=”Buttom3”,fg=”pur
ple”).pack(side=”left”)
btn4=tkinter.Buttom(bottom_frame,text=”Button4”,fg=”Ora
nge”).pack(side=”left”)
CODERZ ACADEMY
END
CODERZ ACADEMY