0% found this document useful (0 votes)
263 views142 pages

PYTHON Document From Dinesh12

The document discusses various topics related to Python including: 1. It introduces the different types of software and languages like system software, application software, utility software, low-level languages like machine language and assembly language, and high-level languages like Python and Java. 2. It describes the different types of translators like interpreters, compilers, and assemblers that are used to convert between high-level and machine languages. 3. It provides an overview of Python, its history, features, applications, advantages, and compares it to Java.

Uploaded by

Dinesh Pitchuka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
263 views142 pages

PYTHON Document From Dinesh12

The document discusses various topics related to Python including: 1. It introduces the different types of software and languages like system software, application software, utility software, low-level languages like machine language and assembly language, and high-level languages like Python and Java. 2. It describes the different types of translators like interpreters, compilers, and assemblers that are used to convert between high-level and machine languages. 3. It provides an overview of Python, its history, features, applications, advantages, and compares it to Java.

Uploaded by

Dinesh Pitchuka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 142

CORE PYTHON NOTES

Software:

There are three types of softwares

1.system software:
Example:OS (windows,unix,linux….)
2.application software:
Examples:
Railway reservations
Airway reservations
Entertainment applications
3.utility software:
Example:
Anti-virus
Data backup
Disk cleaners

Types of languages:
There are two of languages
1.low-level languages:
(a)machine language:
0 indicates absence of electrical pulse.
1 indicates presence of electrical pulse.
(b)assembly language:
It was having mnemonic code.mnemonic codes are either three letter combination or five
letter combination
Example:
START,STOP,ADD,SUB………………..

High-level languages:
Examples:
Java,python

Translators:
It is used to convert high level language code to machine language.
There are three types of translators:
1.interpreter:
It is used to convert high level language code to machine level language by line by line.
ALLA SUSHMA(MCA)
PYTHON TRAINER
Example:python,ruby,perl………….
2.compiler:
It is used to convert high level language code to machine language in single step.
Examples:
C,c++,java…………..
3.assembler:
It is used to convert assembly code to machine language.

Introduction of python
● Python is a high level programming language.
● It is a scripting language.
● It was created by guido van rossum and released in the year 1991 at national research
institute for mathematics and computer science in Netherlands.
● It is system independent language.
● Python name comes from an old BBC television comedy sketch series called MONTY
PYTHONS FLYING SERIES
● It is an open source software.
● Source can be applied or run just in time.
● It is a interpreted language.
● It is derived from many other languages like ABC,C,C++,Algol-68,small talk,unix shell
other scripting languages.

Features of python:
● Easy to use
● Open source
● Supports GUI(Tkinter)
● Supports object oriented programming
o Classes and objects
o Abstraction
o Encapsulation
o Inheritance
o polymorphism
● Cross-platform language
● Large standard library
● Expressive language
ALLA SUSHMA(MCA)
PYTHON TRAINER
Python applications:
● Web applications
● Desktop GUI applications
● Console based applications
● Scientific and numeric applications
● Business applications
● Audio and video and image applications
● 3D CAD applications
● Enterprise applications

Advantages of python:
1.it is a interpreted language
2.dynamically typed
3.free and open source
4.vast libraries support

Interview question:
What is the diff between java and python?
Java Python
1.it is statically typed 1.it is dynamically typed
2.it is compiled language 2.it is interpreted language
3.it is plat form independent 3.it is also platform independent
4.more-libraries and documentation 4.fewer libraries and documentation
5.larger legacy problems 5.less legacy problems

ALLA SUSHMA(MCA)
PYTHON TRAINER
6.java is used to develop in 6.mainly used for data
web,mobile,enterprise applications science,AI,ML,IOT,Deep learning.
7.faster than python 7.fast but usually slower than java.

What companies are using python?


● Google
● Facebook
● Instagram
● Quora
● Netflix
● Dropbox

Games uses python:


● Battlefield2
● Bridge commander
● Civilization iv
● Disney’s toontown online
● Freedom force

Variables or identifiers:
Variable is a name of the memory location where data is stored.variable using a combination
of letters,numbers and underscore.
Rules:
1.name of the variable cannot start with a number. It should start with either alphabet or
underscore.
2.variable names are case sensitive.and can contain alpha numeric characters and the
underscore character.
3.reserved words cannot be used as variable names.
4.no space is given in between the variable name.
Example:
NAME(valid)
Name(valid)
name(valid)
name_1(valid)
_name(valid)
Stu name(invalid)
Stu_name(valid)
3name(invalid)
ALLA SUSHMA(MCA)
PYTHON TRAINER
Char(invalid)

1.Assigning values to the variables:


>>> id=23
>>> name="sushma"
>>> branch="mca"
>>> print(id)
23
>>> print(name)
sushma
>>> print(branch)
Mca

2.multiple assignments:
(a)Assigning single value to multiple variables.
>>> x=y=z=45
>>> print(x)
45
>>> print(y)
45
>>> print(z)
45
(b)assigning multiple values to multiple variables:
>>> a,b,c=89,78,56
>>> print(a)
89
>>> print(b)
78
>>> print(c)
56

Python tokens:
Token:
It is nothing but individual unit of a program.
1.keywords:
True,False,None,and,as,asset,def,class,continue,break,else,finally,elif,del,except,global,for,if,fr
om,import,raise,try,or,return,pass,nonlocal,in,not,is,lambda

2.literals:
ALLA SUSHMA(MCA)
PYTHON TRAINER
1.string literals:
We can use both single and double quotes to represent strings.
>>> a='s'
>>> print(a)
s
>>> name='sushma'
>>> print(name)
sushma
>>> name="mani kumar"
>>> print(name)
mani kumar
>>>str=”””I love my country”””
>>>print(str)
>>> str='''today we are discussing basics in python'''
>>> print(str)
today we are discussing basics in python
>>>

2.numeric literals:
Integer(signed integers):
Numbers(can be both positive and negative) with no fractional part.
Example:345,67890,-456,-789
Long numbers:
Integers of unlimited size
Example:67532356789
Float point:
Real numbers with both integer and fractional part.
Example:34.567,-23.456
Complex numbers:
In the form of a+bj where ‘a’ forms the real part and ‘b’ forms imaginary part of complex
number
Example:45+67j,90+23j

3.boolean literals:
It can have any of the two values:True or Flase

4.special literals
Python contains one special literal i.e None
>>> id=345
ALLA SUSHMA(MCA)
PYTHON TRAINER
>>> name=None
>>> print(id)
345
>>> print(name)
None

5.literal collections:
List:
● List contain items of different data types. Lists are mutable(modifiable).
● The values stored in list are separated by comma(,) and enclosed within square
brackets([])
● Value stored in a list can be retrieved using the slice operator([:])
● The plus sign(+) is the list concatenation and asterisk(*) is the replication operator.
Example:
>>> list=[12,23,34,45]
>>> list1=[45,67,89]
>>> list+list1
[12, 23, 34, 45, 45, 67, 89]
>>> list3=['sushma','mani','chanti','kana']
>>> list4=['shankar','yasodha']
>>> list3+list4
['sushma', 'mani', 'chanti', 'kana', 'shankar', 'yasodha']
>>> list5=[12,34,78.987,'sushma']
>>> list6=[34.234,'chanti']
>>> list5+list6
[12, 34, 78.987, 'sushma', 34.234, 'chanti']
>>> list4*2
['shankar', 'yasodha', 'shankar', 'yasodha']
>>> list1*3
[45, 67, 89, 45, 67, 89, 45, 67, 89]
>>> list=[12,45,67,78,89,90,98,87,76,65]
>>> list[2:9]
[67, 78, 89, 90, 98, 87, 76]
>>> list[5:]
[90, 98, 87, 76, 65]

Tuples:
● Tuple is another form of collection where different type of data can be stored.

ALLA SUSHMA(MCA)
PYTHON TRAINER
● It is similar to list where data is separated by commas. Only the difference is that
list uses square brackets and tuple uses parenthesis.
● Tuples are immutable(not modifiable).
Example:
>>> tuple=('sushma','sowmya','venkat')
>>> tuple1=('padma','deepthi','shankar')
>>> tuple+tuple1
('sushma', 'sowmya', 'venkat', 'padma', 'deepthi', 'shankar')
>>> tuple1*2
('padma', 'deepthi', 'shankar', 'padma', 'deepthi', 'shankar')
>>>

Python operators
Operator is a symbol that performs an operation on one or more operands.A operand is a
variable or a value on which we perform operation.
Example:
A+B
A,B are operands
+ is called operator

1.Arithmetic operators:
(a)Addition(+):
Add the values on either side of the operator.
Example:
>>> 8+12
20
>>> 78+32
110
>>> 90+123
213
>>> 6789+23456
30245

(b)subtraction(-):
Subtracts the value on the right from the one of the left
Example:
>>> 45-12
33
>>> 67-567
ALLA SUSHMA(MCA)
PYTHON TRAINER
-500
>>> 9876-1234
8642
>>>

(c) multiplication(*):
Multiplies the values on either side of the operator
Example:
>>> 56*2
112
>>> 789*12
9468
>>> 12*67
804

(d)division operator(/):
Divides the value on the left by the one on the right notice that division results in a floating
point value.
Example:
>>> 56/2
28.0
>>> 789/12
65.75
>>> -567/23
-24.652173913043477

(e)exponentiation(**):
Raises the first number to the power of the second.
Example:
>>> 4**7
16384
>>> 12**3
1728
>>>

(f)floor division(//):
Divides and returns the integer value of the quotient. It dumps the digits after the decimal.
ALLA SUSHMA(MCA)
PYTHON TRAINER
Example:
>>> 3//4
0
>>> 4//3
1
>>> 10//3
3
(g)modulo(%):
Divides and return the value of the remainder.
Example:
>>> 12.34%4
0.33999999999999986
>>> 789.234%12
9.234000000000037
>>> 0.234%2
0.234
>>> 45%4
1

(2)relational operators:
Here we carries out the comparision between operands. They tell us whether an operand is
greater than the other or lesser or equal or combination of those.
(a)less then(<):
It checks if the value on the left of the operator is lesser than the one on the right.
Example:
>>> 10<20
True
>>> -12<34
True
>>> 34<78
True
>>> 78<12
False
>>> 56.78<12.345
False
>>> 12.345<78.345
True

ALLA SUSHMA(MCA)
PYTHON TRAINER
(b)greater than(>):
It checks if the values on the left of the operator is greater than the one on the right.
Example:
>>> 23>12
True
>>> 67>109
False
>>> 45.678>12.345
True6
>>> 45.123>78.456
False

(c) less than or equal to(<=):


It checks if the value on the left of the operator is lesser than or equal to one of the right.
Example:
>>> 7<=7
True
>>> 6<=7
True
>>> 23.456<=23.456
True
>>> 23.789<=12.345
False

(d)greater than or equal to(>=):


It checks if the value on the left of the operator is greater than or equal to the one on the
right.
Example:
>>> 45.6789>=89.4567
False
>>> 567>=567
True
(e) equal to operator(==):
It checks if the value on the left of the operator is equal to the one on the right. ‘1’ is equal to
the Boolean value true and ‘0’ is equal to the Boolean value false.
Example:
>>> 3==3.0
ALLA SUSHMA(MCA)
PYTHON TRAINER
True
>>> 3==3.45
False
>>> 1==True
True
>>> 7==True
False
>>> 0==False
True

(f)not equal to operator(!= (or) <>):


It checks if the value on the left of the operator is not equal to the one on the right. The
python operator <> does not the same job, but it is removed in python 3.
Example:
>>> 1!=1.0
False
>>> -1<>-1.0
SyntaxError: invalid syntax

3.Assignment operators:
(a)assign(=):
Example:
>>> name='sushma'
>>> print(name)
Sushma

(b)add and assign(+=):


Adds the values on the either side and assign it to the expression on the left.
A+=34🡺A=A+34
Example:
>>> a=34
>>> a+=4
>>> print(a)
38
(c) subtract and assign(-=):
Subtract the value on the right from the value of the left.
Example:
>>> b=12.34
>>> b-=11.12
ALLA SUSHMA(MCA)
PYTHON TRAINER
>>> print(b)
1.2200000000000006

(d)divide and assign(/=):


Divides the value on the left by the one on the right. Then it assign it to the expression on the
left.
Example:
>>> c=345.678
>>> c/=4
>>> print(c)
86.4195

(e)multiply and assign(*=):


Multiplies the values on either sides . Then it assigns it to the expression on the left.
Example:
>>> e=24.67
>>> e*=9
>>> print(e)
222.03000000000003

(f)modulo and assign(%=):


Performs modulo on the values on either side. Then it assigns it to the expression on the left.
Example:
>>> a=45
>>> a%=6
>>> print(a)
3

4.logical operators:
(a)logical AND
A B A and B
0 0 0
1 0 0
0 1 0
1 1 1

Example:
ALLA SUSHMA(MCA)
PYTHON TRAINER
>>> a=6>5 and 28>19
>>> print(a)
True
>>> b=12.345>34.567 and 67.234>12.345
>>> print(b)
False

(b)logical OR:
A B A or B
0 0 0
1 0 1
0 1 1
1 1 1

Example:
>>> a=7>7 or 2>-1
>>> print(a)
True

(c) logical NOT:


It converts true to false and false to true
Example:
>>> a=not(1)
>>> print(a)
False
>>> b=not(0)
>>> print(b)
True

Membership operators:
These operators test whether a value is a member of a sequence. The sequence may be a list
or a string or tuple.
in operator:
it checks if a value is a member of a sequence or not.
Example:
>>> names=['sushma','sowmya','chanti']
>>> 'kanna' in names
ALLA SUSHMA(MCA)
PYTHON TRAINER
False
>>> 'chanti' in names
True

Not in operator:
It checks if a value is not a member of sequence.
Example:
>>> 'kanna' not in names
True
>>> 'chanti' not in names
False

Identity operators:
is operator: returns true if both variables are the same object.
Example:
>>> x=5
>>> type(x) is int
True
>>> x=45.67
>>> type(x) is float
True
>>> x='sushma'

is not operator:
returns true if both variables are not the same object.
Example:
>>> x=45.678
>>> type(x) is not int
True

Bitwise operators:
(a)bitwise AND(&):it returns 1 if both the bits are 1 otherwise 0.
Example:
>>>10&7
>>>2
Explanation:
A=10🡺1010(binary)
ALLA SUSHMA(MCA)
PYTHON TRAINER
B=7🡺 0111(binary)
A&B🡺 0010
🡺2

(b)Bitwise OR(|):
It returns 1 if any of the bits is 1. If both the bits are 0 then it returns 0.
Example:
>>> 10|7
15
Explanation:
A=10🡺1010
B=7 🡺 0111
A|B🡺 1111
🡺15

(c) bitwise XOR(^):


A B A^B
0 0 0
0 1 1
1 0 1
1 1 0

Example:
>>> 10^7
13
Explanation:
A=10🡺1010
B= 7🡺 0111
A^B🡺 1101
🡺13

(d)bitwise one complement(~):


Ones complement of a number ‘A’ is equal to –(A+1)
Example:
>>> ~10
-11
>>> ~-67
66
Explanation:
ALLA SUSHMA(MCA)
PYTHON TRAINER
A=10🡺1010
~A=~1010
=-(1010+1)
=-(1011)
=-11
(e)shift left operator(<<):
If shifts the left operand bits towards the left side for the given number of times in the right
operand . in simple terms, the binary number is appended with 0’s at the end on right side.
Example:
>>> 10<<2
40
>>>
Explanation:
A=10🡺1010
A<<2=1010<<2
=101000
=40(decimal)

(f)bitwise right shift operator(>>):


It is exactly opposite of the left shift operator.. then left side operand bits are moved towards
the right side for the given number of times. In simple terms, the right side bits are removed.
Example:
>>> 10>>2
2
Explanation:
A=10🡺1010
A>>2🡺1010>>2
🡺 0010
🡺2(decimal)

Python comments:
Giving brief description of a program.
1.single line comments(#)
2.multi-line comments(‘’’……………………………..”’)
Example:
‘”today we are Discussing Python’’’ Concepts”’ Discussing comments”’(invalid)
‘”today we are discussing comments”’(valid)

Taking input from keyboard in python


ALLA SUSHMA(MCA)
PYTHON TRAINER
🡪there are two types of inbuilt functions to read from the keyboard.
● raw_input(prompt)
● input(prompt)

(a)raw_input(prompt):
1.it supports in python 2.x.
2.this function takes exactly what is a type from the keyboard. Converted it to string and
then return it to the variable in which we want to store.
Example:
name=raw_input("enter the name:")
NameError: name 'raw_input' is not defined
Note:
raw_input() is deprecated in python 3.x.

2.input():
This function automatically identifies whether user entered a string or list. If the input
provided is not correct then either syntax error or exception is raised in python.
Type casting:
Converting one data type into another data type.
Example:
>>> num=input("enter a number:")
enter a number:89
>>> print(type(num))
<class 'str'>
>>> num=45.678
>>> print(type(num))
<class 'float'>
>>> num=input("enter any number:")
enter any number:45.678
>>> print(type(num))
<class 'str'>
>>> name=input("enter name:")
enter name:'sushma'
>>> print(type(name))
<class 'str'>

1.typecasting the input to integer:


Example:
>>> num1=int(input())
ALLA SUSHMA(MCA)
PYTHON TRAINER
456
>>> print(num1)
456
>>> print(type(num1))
<class 'int'>

2.Typecasting the input to float:


Example:
>>> num1=float(input())
67.8943
>>> print(num1)
67.8943
>>> print(type(num1))
<class 'float'>

3.typecasting the input to string:


All kind of input can be converted to string type whether they are float or integer. We
make use of keyword str for typecasting.
Example:
>>> num=str(input())
789
>>> print(num)
789
>>> print(type(num))
<class 'str'>
>>> num1=str(input())
45.123
>>> print(num1)
45.123
>>> print(type(num1))
<class 'str'>

Taking multiple inputs from user in python:


There are two methods to accept multiple values from the keyboard.
● Using split()
● Using list comprehension
1.using split():
This function helps in getting multiple values from the user. It breaks the input by the specific
separator. If separator is not provided then any white space is a separator.
ALLA SUSHMA(MCA)
PYTHON TRAINER
Syntax:
Input().split(separator,maxsplit)
#type1:
>>> x,y=input("enter two values:").split()
enter two values:67 78
>>> print(x)
67
>>> print(y)
78
>>> a,b=input("enter 2 values:").split(',')
enter 2 values:23,34
>>> print(a)
23
>>> print(b)
34
>>> a,b=input("enter 2 values:").split('&')
enter 2 values:34&67
>>> print(a)
34
>>> print(b)
67
#type-2:
Example:
>>> a,b=input("enter two values:").split()
enter two values:78 89
>>> print("first number is {} and second number is {}".format(a,b))
first number is 78 and second number is 89

#type-3:taking two inputs at a time and type casting using the list function
Example:
>>> list1=list(map(int,input("enter values:").split()))
enter values:56 78 90 12 13 14 15 56
>>> print(list1)
[56, 78, 90, 12, 13, 14, 15, 56]

2.using list comprehension:


We can create lists just like mathematical statements one line only. It is also used in getting
multiple inputs from user.
#type-1:taking three inputs at a time
ALLA SUSHMA(MCA)
PYTHON TRAINER
Example:
>>> x,y,z=[int(x) for x in input("enter three values:").split()]
enter three values:67 89 90
>>> print(x)
67
>>> print(y)
89
>>> print(z)
90

#type-2:by using format method


Example:
>>> x,y=[int(x) for x in input("enter 2 values:").split()]
enter 2 values:56 67
>>> print("first number {} and second number {}".format(x,y))
first number 56 and second number 67

#type-3:
Example:
>>> z=[int(x) for x in input("enter list of values:").split()]
enter list of values:67 45 23 12 2 3 90 345 678
>>> print(z)
[67, 45, 23, 12, 2, 3, 90, 345, 678]

‘end’ parameter in print():


print() comes with a parameter called ‘end’. By default, the value of this parameter is ‘\n’. i.e
the new line character.you can end a print statement with any character/string using this
parameter.
Example:
#type-1:
print("magneq",end="")
print("software")
print()

#type-2:
print("magneq",end="\n")
print("software")
ALLA SUSHMA(MCA)
PYTHON TRAINER
print()

#type-3:
print("magneq",end="#")
print("software")
print()

‘sep’ parameter in print():


It is implemented in python 3.x or later
It is used for formatting the out string.
print() in python is space by default ,which can be modified and can be made to any character
or integer or string as per your choice.
Example:
print('s','u','s','h','m','a',sep=' ')
print('17','05','1990',sep='-')
print("sushma","alla",sep='#')
output:
sushma
17-05-1990
sushma#alla

Example:
print('s','u','s','h','m','a',sep=' ',end="\n")
print('17','05',sep='-',end='-1990\n')
print("sushma","alla",sep='#',end=' ')
print("sowmya")

sushma
17-05-1990
sushma#alla sowmya

output formatting:
(a)formatting output using string modulo operator(%):
The modulo operator can also used for string formatting. It is much like a printf().
Example:
>>> print("%10.3E"%(3456.789123))
3.457E+03
ALLA SUSHMA(MCA)
PYTHON TRAINER
>>> print("salary:%5.2f"%(345.234567))
salary:345.23

(b)formatting output using format method:


This method let us concatenate elements within an output through positional formatting.
Example:
>>> print('iam learning {}'.format('python concepts'))
iam learning python concepts
>>> print('{0} and {1}'.format('sushma','alla'))
sushma and alla

control structures
conditional statements:
(a) If statement:
If the condition is satisfied it prints the statement in print(), if condition is not satisfied
then it will not print anything.
Syntax:
if condition:
statements
Example:
a=-13
if a>=0:
print("given number is greater than zero")

(b)if else:
if condition:
statements
else:
statements
Example:
a=13
if a>=0:
print("given number is greater than zero")
else:
print("given number is not greater than zero")
Example:2
num=23
if num%2==0:
print("number is even")
ALLA SUSHMA(MCA)
PYTHON TRAINER
else:
print("number is odd")

(c) else if ladder:


Syntax:
if condition:
Statements
elif condition:
statements
………….
elif condition-n:
statements-n
else:
statements
Example:
marks=68
if marks<34 and marks>=0:
print("failed")
elif marks<60 and marks>=35:
print("C grade")
elif marks<80 and marks>=60:
print("B grade")
elif marks<=100 and marks>=80:
print('A grade')
else:
print("invalid marks")

for loop:
Syntax:
for <variable_name> in <sequence>:
statements
Example:
for a in range(0,10):
print(a)

nested for loop:


Syntax:
for <variable_name> in <sequence>:
ALLA SUSHMA(MCA)
PYTHON TRAINER
for <variable_name> in <sequence>:
statements
Example:
for i in range(0,5):
for j in range(0,i+1):
print("*",end="")
print()
output:
*
**
***
****
Example-2:
k=1
for i in range(0,5):
for j in range(0,k):
print("*",end="")
k=k+2
print()
output:
*
***
*****
*******

Example-3:
n=1
for i in range(0,5):
for j in range(0,i+1):
print(n,end="")
n=n+1
print()
output:
1
22
333
4444

ALLA SUSHMA(MCA)
PYTHON TRAINER
55555

Example:4
for i in range(0,5):
num=1
for j in range(0,i+1):
print(num,end="")
num=num+1
print()
output:
1
12
123
1234
12345

Example-5:
val=65
for i in range(0,5):
for j in range(0,i+1):
ch=chr(val)
print(ch,end="")
val=val+1
print()
output:
A
BC
DEF
GHIJ
KLMNO

Example-6:
val=65
for i in range(0,5):
for j in range(0,i+1):
ch=chr(val)
print(ch,end="")
val=val+1
print()
ALLA SUSHMA(MCA)
PYTHON TRAINER
output:
A
BB
CCC
DDDD
EEEEE
-
While loop:
Syntax:
while <expression>:
statements
#step-1:initialize the value to the variable
#step-2:check the condition
#step-3: if condition is satisfied, it print the value
#step-4: increment the value
#step-5:repeat 1 to 4 steps until the condition is satisfied.
Example:
x=0
while x<10:
print(x)
x=x+1
Example-2:
x=10
while x>=1:
print(x)
x=x-1

break statement:
it is a jumping statement that is used to pass the control to the end of the loop.
Example:
for i in [2,3,4,5,6,7]:
if i==5:
print("element found")
break
print(i)

continue statement:
Example:
for i in [2,3,4,5,6,7]:
ALLA SUSHMA(MCA)
PYTHON TRAINER
if i==5:
print("element found")
continue
print(i)

Strings
🡪python strings are immutable(not modifiable). In python strings is enclosed with single and
double quotes. ‘space ‘ is also considered as a character in strings.
🡪String are stored as individual characters in a contiguous memory locations.

🡪the benefit of using strings is that it can be accessed from both the directions in forward and
backward.
1.forward indexing starts with 0 to n-1
2.backward indexing starts with -1 to –n

String operators are three types:


1.Basic operators:
There are 2 types of basic operators
a.’+’ (concatenation operator):
It concatenates two strings and forms a new string
Example:
>>> 'alla'+'sushma'
'allasushma'
>>> 'l love'+'country'
'l lovecountry'
b.’*’ (replication operator):

ALLA SUSHMA(MCA)
PYTHON TRAINER
it is used to repeat a string number of times.
Example:
>>> 5*'mani'
'manimanimanimanimani'

2.member ship operators:


a)in:it returns true if a character or the entire sub string is present in the specified string.
Otherwise false.
b)not in :it returns true if a character or entire substring does not exist in the specified string,
otherwise false.
Example:
>>> str1='sushma'
>>> str2='mmmmm'
>>> str3='hma'
>>> str2 in str1
False
>>> str3 in str1
True
>>> str3 not in str1
False
>>> str2 in str1
False

Slice notation(:) :
It can be defined as substring which is the part of the string.
Syntax:
<string_name>[sart_index: end_index]
<string_name>[:end_index]
<string_name>[start_index:]
<string_name>[start_index:end_index:stepvalue]
Example:
>>> string="i love my country"
>>> string[0:7]
'i love '
>>> string[:9]
'i love my'
>>> string[6:15]
' my count'
>>> string[2:5:4]
ALLA SUSHMA(MCA)
PYTHON TRAINER
'l'
>>> string[-1:-4]
''
>>> string[-4:-1]
'ntr'

String methods:
1.capitalize():it capitalizes the first character of the string.
Example:
>>> 'manikumar'.capitalize()
'Manikumar'
>>> 'i love my country'.capitalize()
'I love my country'
>>> "i love my country".title()
'I Love My Country'
>>>

2.count(string,begin,end):counts no of times substring occurs in a string between begin and


end index.
Example:
>>> string="magneq software"
>>> substr="a"
>>> print(string.count(substr,0,15))
2
>>> print(string.count(substr))
2

3.endswith(suffix,begin,end):returns a Boolean value if the string terminates with given


suffix between begin and end.
Example:
>>> string='i love my country'
>>> substr='country'
>>> substr1='name'
>>> print(string.endswith(substr))
True
>>> print(string.endswith(substr1))
False

ALLA SUSHMA(MCA)
PYTHON TRAINER
4.find(substring,beginindex,endindex):it returns the index value of the string where substring
is found between begin and end index.
Example:
>>> str='welcome to magneq software'
>>> substr='magneq'
>>> print(str.find(substr))
11
>>> print(str.find(substr,3,17))
11
>>> substr3="kumar"
>>> print(str.find(substr3))
-1

5.index(string,beginindex,endindex):
Same as find(). Except it raises an exception if string is not found.
Example:
>>> str='i love my country'
>>> substr='my'
>>> print(str.index(substr,10,17))
ValueError: substring not found-
>>> print(str.index(substr,0,15))
7

6.isalnum(): it returns if characters in the string are alphanumeric.alphabets and numbers and
there is atleast 1 character, otherwise it returns false.
Example:
>> str='sushma123'
>>> print(str.isalnum())
True

7.isalpha(): it returns true when all the characters are alphabets and there is atleast one
character, otherwise false.
Example:
>>> str='sushma'
>>> print(str.isalpha())
True
>>> str='sushma123'
>>> print(str.isalpha())
False
ALLA SUSHMA(MCA)
PYTHON TRAINER
8.isdigit():it returns true if all the characters are digits and there is atleast one character
otherwise false.
Example:
>>> str='23456'
>>> print(str.isdigit())
True
>>> str='2345s'
>>> print(str.isdigit())
False

9.islower():it checks whether the given string is lower case or not.


Example:
>>> str='sushma'
>>> print(str.islower())
True
>>> str='Sushma'
>>> print(str.islower())
False
>>> str='SUSHMA'
>>> print(str.islower())
False

10.isupper():it checks whether a string is upper case or not


Example:
>>> str='SUSHMA'
>>> print(str.isupper())
True
>>> str='sUSHMA'
>>> print(str.isupper())
False

11.isspace():it returns true if the character of a string are whitespace otherwise false.
Example:
>>> str=' '
>>> print(str.isspace())
True
>>> str=''
>>> print(str.isspace())
ALLA SUSHMA(MCA)
PYTHON TRAINER
False
>>> str='i love'
>>> print(str.isspace())
False

12.len(string): it returns the length of the string.


Example:
>>> str="welcome to magneq software"
>>> print(len(str))
26

13.lower(): it converts uppercase letters to lower case.


Example:
>>> str='SUSHMA'
>>> print(str.upper())
SUSHMA
>>> print(str.lower())
sushma
>>> str='SuShMa'
>>> print(str.lower())
sushma

14.upper(string): it converts all the characters in string to upper case.


Example:
>>> str="sushma"
>>> print(str.upper())
SUSHMA
>>> str="suSHMa"
>>> print(str.upper())
SUSHMA
>>> str="i LOVE my COUNTRY"
>>> print(str.upper())
I LOVE MY COUNTRY

15.startswith(Str,begin,end): returns a Boolean value if the string starts with given str
between begin and end index.
Example:
>>> str='learning python concepts'
>>> substr='learning'
ALLA SUSHMA(MCA)
PYTHON TRAINER
>>> substr='concepts'
>>> print(str.startswith(substr,0,45))
False
>>> substr1='learning'
>>> print(str.startswith(substr,0,45))
False
>>> print(str.startswith(substr1,0,45))
True

16.swapcase():inverts case of all characters in a string.


Example:
>>> string='sUsHmA'
>>> print(string.swapcase())
SuShMa

17.lstrip(): remove all leading whitespaces of a string. It can also be used to remove particular
character from leading.
Example:
>>> string='$$$$$$$sushma$$$$$$$$$$$$'
>>> print(string.lstrip('$'))
sushma$$$$$$$$$$$$
>>> string='susususususushmamamama'
>>> print(string.lstrip('su'))
hmamamama
>>> string=' sushma'
>>> print(string.lstrip(' '))
Sushma

18.rstrip():remove all trailing white spaces of a string. It can also be used to remove particular
character from trailing.
Example:
>>> string='sushma*******'
>>> print(string.rstrip('*'))
sushma
>>> string='sushma '
>>> print(string.rstrip(' '))
Sushma

String template class in python:


ALLA SUSHMA(MCA)
PYTHON TRAINER
It allows us to create simplified syntax for output statement. The format uses placeholder
names formed by $ with python identifiers(alphanumeric characters and underscore).
substitute():it raises a keyError when particular placeholder is not supplied in a dictionary or a
keyword argument.
safe_substitute():it will leave placeholders unchanged if data is missing.

Example:
from string import Template
t=Template('x is $x')
print(t.substitute({'x':4}))

Example-2:
from string import Template
student=[('sushma',87),('mani',99),('chanti',98)]
t=Template('hi $name, you have got $marks marks')
for i in student:
print(t.substitute(name=i[0],marks=i[1]))

string formatting in python using %:


the formatting using % is similar to that of printf in C-programming
%d—integers
%s—strings
%u—unsigned
%f—float
%c—char
%n—new line
%o—octal numbers
%x—hexadecimal
%r—raw data
Example:
variable='15'
string="values as string=%s"%(variable)
print(string)
print("value of raw_data=%r"%(variable))
variable=int(variable)
string="variable as an integer=%d"%(variable)
print(string)
ALLA SUSHMA(MCA)
PYTHON TRAINER
print("variable float=%f"%(variable))
print("variable as hexadecimal=%x"%(variable))
print("variable as octal=%o"%(variable))

Arrays
🡪it is a collection of single data type.
🡪we can use lists to represent arrays
🡪if you want to use real arrays in python,you need to use NumPy’s array data structures. For
mathematical problems .
Installing numpy module:
C:\Users\Y.CHARAN RAJ\AppData\Local\Programs\Python\Python37\Scripts>pip install
numpy
Requirement already satisfied: numpy in c:\users\y.charan
raj\appdata\local\programs\python\python37\lib\site-packages (1.18.5)
Creating an array:
Arr=[12,23,34,45,56,67]
Arr1=[‘sushma’,’mani’,’chanti’]
Arr2=[12,’sushma’,23.456]
🡪index is the position of element in an array, arrays are zero-indexed. The elements position
starts with zero and end with n-1.
🡪Arrays supports negative indexing. This means the index value of -1 give the last element
and -2 gives the second element of last element of the array.

Example:
>>> arr=[12,23,34,45,56]
>>> print(arr[1])
23

ALLA SUSHMA(MCA)
PYTHON TRAINER
>>> print(arr[4])
56
>>> print(arr[-1])
56
>>> print(arr[-4])
23
Methods:
1.len():it is used to findout length of the given array.
Example:
>>> arr=[56,78,89,90,12,23]
>>> print(len(arr))
6
>>> data=["apple","guva","grapes","pineapple","kiwi"]
>>> len(data)
5
>>> data=[23.4,45.6,78.9]
>>> len(data)
3
>>> data=[]
>>> len(data)
0
>>>

2.append():to add new element to an already existing array.


Example:
>>> arr=[23,34,45]
>>> arr.append(90)
>>> print(arr)
[23, 34, 45, 90]

3.remove(): it allows us to delete elements from an array. Similarly we can use ‘del’ operator
and pop() methods to remove elements in array.
Example:
>>> arr=[67,89,90,56,45,34,23]
>>> arr.remove(34)
>>> print(arr)
[67, 89, 90, 56, 45, 23]
>>> arr.pop()
23
ALLA SUSHMA(MCA)
PYTHON TRAINER
>>> print(arr)
[67, 89, 90, 56, 45]
>>> del arr[2]
>>> print(arr)
[67, 89, 56, 45]

4.modifying the elements of the array: we can change values of the elements with in an array.
Example:
>>> fruits=['apple','mango','grapes','guva']
>>> fruits[1]='pineapple'
>>> print(fruits)
['apple', 'pineapple', 'grapes', 'guva']
>>> fruits[-2]='orange'
>>> print(fruits)
['apple', 'pineapple', 'orange', 'guva']

‘+’ operator: it concatenate two arrays


‘*’ operator:it is used to repeat the elements multiple times.
Example:
>>> arr=[4,5,6]
>>> arr+=[7,8,9]
>>> print(arr)
[4, 5, 6, 7, 8, 9]
>>> arr*5
[4, 5, 6, 7, 8, 9, 4, 5, 6, 7, 8, 9, 4, 5, 6, 7, 8, 9, 4, 5, 6, 7, 8, 9, 4, 5, 6, 7, 8, 9]

Slicing an array:
>>> comp=['hp','dell','samsung','sansui','ascer','apple']
>>> comp[0:3]
['hp', 'dell', 'samsung']
>>> comp[0:]
['hp', 'dell', 'samsung', 'sansui', 'ascer', 'apple']
>>> comp[:5]
['hp', 'dell', 'samsung', 'sansui', 'ascer']
>>> comp[-5:-1]
['dell', 'samsung', 'sansui', 'ascer']
>>> comp[-1:-5]
[]
ALLA SUSHMA(MCA)
PYTHON TRAINER
>>> data=[1,2,3,4,5,6,7,8,9,10,11,12,23,34,45,56]
>>> data[0:10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> data[4:]
[5, 6, 7, 8, 9, 10, 11, 12, 23, 34, 45, 56]
>>> data[:15]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 23, 34, 45]
>>> data[-1:-4]
[]
>>> data[-4:-1]
[23, 34, 45]
>>> data[::-1]
[56, 45, 34, 23, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> data[0:20:3]
[1, 4, 7, 10, 23, 56]
>>>

Creating multidimensional arrays:


Matrix representation in python:
Accessing elements of the matrix in python by using list index.
Example:
>>> mat=[['mani',80,99,67,78,88],['sushma',99,98,97,96,95],
['anil',91,87,76,98,90]]
>>> print(mat[0])
['mani', 80, 99, 67, 78, 88]
>>> print(mat[-2])
['sushma', 99, 98, 97, 96, 95]
>>> print(mat[2][3])
76
>>> print(mat[-3][-2])
78

Changing elements of a matrix:


Example
>>> mat=[['mani',80,99,67,78,88],['sushma',99,98,97,96,95],
['anil',91,87,76,98,90]]

>>> b=mat[0]
>>> print(b)
ALLA SUSHMA(MCA)
PYTHON TRAINER
['mani', 80, 99, 67, 78, 88]
>>> b[2]=34
>>> print(b)
['mani', 80, 34, 67, 78, 88]
>>> mat[2]=['sowmya',99,98,97,96,95]
>>> print(mat)
[['mani', 80, 34, 67, 78, 88], ['sushma', 99, 98, 97, 96, 95], ['sowmya', 99, 98, 97, 96, 95]]
>>> mat[0][4]=99
>>> print(mat)
[['mani', 80, 34, 67, 99, 88], ['sushma', 99, 98, 97, 96, 95], ['sowmya', 99, 98, 97, 96, 95]]

Adding a new row in the matrix in python using append():


Example:
>>> from numpy import *
>>> mat=[['mani',80,99,67,78,88],['sushma',99,98,97,96,95]]
>>> mat=append(mat,[['somu',90,91,92,93,94]],0)

>>> print(mat)
[['mani' '80' '99' '67' '78' '88']
['sushma' '99' '98' '97' '96' '95']
['somu' '78' '89' '98' '90' '99']]

Adding a new column in the matrix for marks using insert():


Example:
>>> mat=insert(mat,[6],[[87],[86],[85]],axis=1)
>>> print(mat)
[['mani' '80' '99' '67' '78' '88' '87']
['sushma' '99' '98' '97' '96' '95' '86']
['somu' '78' '89' '98' '90' '99' '85']]

Adding a row with concatenation operator:


Example:
>>> a=[['anil',90,98,97,96,95]]
>>> a=a+[['somu',87,86,85,84,65]]
>>> print(a)
[['anil', 90, 98, 97, 96, 95], ['somu', 87, 86, 85, 84, 65]]

ALLA SUSHMA(MCA)
PYTHON TRAINER
LISTS
● Lists are the data structures that is capable of holding different data types of
data(heterogeneous elements).
● It is mutable.i.e python will not create a new list if we modify an element in the list.
● Different operations like insertions and deletions can be performed on lists.
● It is enclosed with in square brackets(‘[]’).
● The elements are stored in the index basis with starting zero
● An empty list in python takes 72 bytes.

Example:
>>> l=[12,13,14,45,56,67,78,89,90,1,2,3,4,45]
>>> l[0:4]
[12, 13, 14, 45]
>>> l[0:]
[12, 13, 14, 45, 56, 67, 78, 89, 90, 1, 2, 3, 4, 45]
>>> l[:7]
[12, 13, 14, 45, 56, 67, 78]
>>> l[::-1]
[45, 4, 3, 2, 1, 90, 89, 78, 67, 56, 45, 14, 13, 12]
>>> l[-4:-1]
[2, 3, 4]
>>> l[-1:-4]
[]
>>> l[2:15:2]#considering step value
[14, 56, 78, 90, 2, 4]
>>>
List operators:
1.Adding lists:
Lists can be added by using concatenation operator(+) to join two lists.
Example:
>>> data1=[78,89,90]
>>> data2=[76,75,74]
>>> data1+data2
[78, 89, 90, 76, 75, 74]

2.replication operator(*):
Example:
>>> data=[23,34,45]
>>> data*5
ALLA SUSHMA(MCA)
PYTHON TRAINER
[23, 34, 45, 23, 34, 45, 23, 34, 45, 23, 34, 45, 23, 34, 45]

1.updating elements in a list:


To update or change the value of particular index of a list , assign the value to the particular
index of the list.
Syntax:
<list_name>[index]=<value>
Example:
>>> data=[78,89,90,56]
>>> data[2]="78"
>>> print(data)
[78, 89, '78', 56]
>>> data[2]=89.234
>>> print(data)
[78, 89, 89.234, 56]
>>> data[3]="sushma"
>>> print(data)
[78, 89, 89.234, 'sushma']

2.Appending an element into the list:


This method is used to add ‘n’ element at the end of the existing elements.
Syntax:
<list_name>.append(item)
Example:
>>> list1=["sushma","sowmya","anil"]
>>> list1.append("mani")
>>> print(list1)
['sushma', 'sowmya', 'anil', 'mani']
>>> list1.append(["anil","mani"])
>>> print(list1)
['sushma', 'sowmya', ['anil', 'mani']]

3.deleting elements from the list:


It is used to delete an element from the list . it can also be used to delete all items from start
index to end index.
Example:
>>> list1=[23,'sushma',67.87654,9896768757]
ALLA SUSHMA(MCA)
PYTHON TRAINER
>>> del list1[3]
>>> print(list1)
[23, 'sushma', 67.87654]
>>> del list1[0:3]
>>> print(list1)
[]

Functions:
1.min(list):returns min value from the list given.
Example:
>>> list=[34,'sushma','r',9876546786,34.6785]
>>> print(min(list))
TypeError: '<' not supported between instances of 'str' and 'int'
>>> list=[23,56,12,1,0,56]
>>> print(min(list))
0
>>> list1=['mani','sushma','somu']
>>> print(min(list1))
mani

2.max(list):returns the largest value in the given list.


Example:
>>> list1=[98.76,45,23,1234]
>>> print(max(list1))
1234
>>> list=['sushma','somu','anil']
>>> print(max(list))
sushma
>>> list=[90.456,87.6754,78.345,123.345]
>>> print(max(list))
123.345

3.len(list):it returns number of elements in list


Example:
>>> list1=[34,45,56,67]
>>> print(len(list1))
4

ALLA SUSHMA(MCA)
PYTHON TRAINER
Methods:
1.index(object):returns the index value of the object.
Example:
>>> list=[89,'sushma',89.345,876876]
>>> print(list.index(89.345))
2

2.count(object): it returns the number of times an object is repeated in list.


Example:
>>> list=[89,34,56,78,89,23,89]
>>> list.count(89)
3
>>> list.count(78)
1

3.pop(object): returns the last object or the specified index object . it removes the popped
object .
Example:
>>> list=[45,56,67,78,8,9,99]
>>> list.pop()
99
>>> list.pop(3)
78

4.insert(index,value):
Insert an value at the given index.
Example:
>>> list=[34,45,56,67,78,89]
>>> list.insert(2,12)
>>> print(list)
[34, 45, 12, 56, 67, 78, 89]
>>> list=['sushma','somu','chanti','anil']
>>> list.insert(1,'mani')
>>> print(list)
['sushma', 'mani', 'somu', 'chanti', 'anil']

5.extend(sequence):it adds the sequence to existing list


ALLA SUSHMA(MCA)
PYTHON TRAINER
Example:
>>> data1=[34,56,67]
>>> data2=[12,13,14]
>>> data1.extend(data2)
>>> print(data1)
[34, 56, 67, 12, 13, 14]

6.remove(value): it will remove the element from the list


Example:
>>> list1=['sushma','somu','chanti','anil','kanna']
>>> list1.remove('anil')
>>> print(list1)
['sushma', 'somu', 'chanti', 'kanna']

7.reverse(): reverse the position of all the elements of a list.


Example:
>>> list=[45,67,89,90]
>>> list.reverse()
>>> print(list)
[90, 89, 67, 45]

8.sort():it is used to sort the elements in the list.


Example:
>>> list1=[89,45,7,12,100,1]
>>> list1.sort()
>>> print(list1)
[1, 7, 12, 45, 89, 100]

FUNCTIONS

🡪A function is a group of related statements that performs a specific task.


🡪in python a function is defined using ‘def’ keyword.
🡪there are two types of functions
● Built in functions: These functions are part of the python programming. There are 68
built-in functions.
Example:print(),dir(),abs(),length()……………………………
● User-defined functions:these functions are made by user as there requirement.
Advantages:
ALLA SUSHMA(MCA)
PYTHON TRAINER
● Code reusability
● Reducing duplications of code
● Decomposing complex problems into smaller pieces
● Abstraction
● Easy debugging
Syntax:
def <function-name>(arguments):
statements
……………
return statement

● ‘def’ is a keyword used to define a function.


● Def keyword is followed by a function.
● Function can contain parameters or without parameters.
● Return statement is optional
● The return statement is used to return the value. A function can have only one return.
● By using return statement we can return multiple values.

Interview question:
What is the difference between method and function?
Method Function
1.Associated with objects 1.not associated with any object
2.cannot invoke by its name 2.can invoke by its name
3.dependent on class 3.independent
4.require ‘self’ 4.do not require ‘self’

Function calling:
🡪A function must be defined before the function call, otherwise the python interpreter gives
an error.
🡪after function is created, we can call it from another function.
Example:
def hello():#function definition
print("today we are discussing functions concept")
hello() #function calling

return statement:
🡪it terminates the function execution and transfers the result where the function is called .
🡪the return statement cannot be used outside of the function.
Syntax:
ALLA SUSHMA(MCA)
PYTHON TRAINER
return[expression_list]
🡪it contain expression which gets evaluated and value is returned to the caller function.
🡪if return statement has no expression (or) does not exist itself in the function then it returns
None object.
Example:creating a function without return statement.
def mul():
a= 10
b=5
c=a*b
print(mul())
output:None

Example-2:
def mul():
a=10
b=5
c=a*b
return c
print("multiplication is:",mul())

Example-2:
def add():#function definition
a=10
b=20
c=a+b
d=a*b
e=a/b
f=a%b
return c,d,e,f
print(add())

Example-3:
def add():#function definition
a=10
b=20
return a+b,a*b,a/b,a**b
print(add())

arguments passing in functions:


ALLA SUSHMA(MCA)
PYTHON TRAINER
1.we can pass any no of arguments, but they must separated them with comma.
Example:
def name(person):
print("hi",person)
name("sushma")

Example-2:
#write a function to calculate the area of rectangle
def rect(l,b):
return l*b
l=int(input("enter length:"))
b=int(input("enter breath:"))
print("area of rectangle:",rect(l,b))
output:
enter length:56
enter breath:89
area of rectangle: 4984

Interview question:
What is the diff between parameter and arguments?
Parameter :
It is a variable defined by a method that receives a value when a method is called.
Arguments:
It is a value that is passed to a method when it is invoked.

Types of arguments:
1.required arguments:
● These are the arguments which are required to be passed at the time of function
calling with the exact match of their positions in the function call and function
definition.
● If arguments are not provided in the function call or the position of arguments is
changed then python interpreter will show an error.
Example:
def simple(p,t,r):
return (p*t*r)/100
p=float(input("enter principle:"))
r=float(input("enter rate:"))
t=float(input("enter years:"))
ALLA SUSHMA(MCA)
PYTHON TRAINER
print("simple_interest:",simple(p,r,t))

Example-1:
def sub(a,b):
return a-b
print(sub(45))
output:
TypeError: sub() missing 1 required positional argument: 'b'

2.default arguments:
If the value of any of the argument is not provided at the function call, that argument can be
initialized with the value given in the definition even if the argument is not specified at the
function call.
Example:
def clg(clg_name,clg_id=234):#function definition
print("college name is:",clg_name,"college id is:",clg_id)
clg(clg_name="pydah")#function call
output:
college name is: pydah college id is: 234

Example:2
def clg(clg_name,clg_id=234):#function definition
print("college name is:",clg_name,"college id is:",clg_id)
clg(clg_name="pydah")#function call
clg(clg_id=7654,clg_name="avanthi")#the value of id is overriden
output:
college name is: pydah college id is: 234
college name is: avanthi college id is: 7654

3.arbitary arguments(*args) (or) variable –length arguments:


By using this function we can pass any number of arguments.
Example:
def fnames(*fruits):
print("types of arguments:",type(fruits))
for name in fruits:
print(name)
fnames("apple","grapes","mango","guva")
ALLA SUSHMA(MCA)
PYTHON TRAINER
output:
types of arguments: <class 'tuple'>
apple
grapes
mango
guva

note:
python provides us the flexibility to offer the comma separated values which are internally
treated as tuples at the functional call . the tuple is an iterable sequence.

4.keyword arguments(**kwargs):
The name of the arguments is treated as the keywords and matched in the function calling
and definition. If the same match is found , the values of arguments are copied in the function
definition:
Example:
def person(name,desg):
print("person_name:",name," and person desg:",desg)
person(name="manikumar",desg="business")
output:
person_name: manikumar and person desg: business

Example-1:
def simple(p,t,r):
return (p*t*r)/100
print("simple interest:",simple(t=10,r=6,p=2000))
output:
simple interest: 1200.0

Example-3: **kwargs stores the arguments in the dictionary format.


def names(**kwargs):#function definition
print(kwargs)
names(name="sushma")
names(name="anil",desg="software")
output:
{'name': 'sushma'}
{'name': 'anil', 'desg': 'software'}

Scope of the variables:


ALLA SUSHMA(MCA)
PYTHON TRAINER
The variables are defined in two ways
1.local variables:
The variable defined inside a function is known as local variables.
Example:
def msg():
name="sushma"#local variable
print(name)
msg()
print(name)

2.global variable:
The variable defined outside of any function is known as global variable.
Example:
def cal(*args):
sum=0#local declaration
for arg in args:
sum=sum+arg
print("addition is:",sum)
sum=0#global variable
cal(78,89,90,45,34)
print("sum of values:",sum)

lambda functions:
● It is also called as anonymous functions.
● It can take any number of arguments, but they contain only single expression.
● A expression is a piece of code executed by the lambda function, which may or may
not return any value.
● It can be used to return function objects
Syntax:
lambda arguments:expression

Example:
power=lambda num:num**3
print(power(5))

Example:
product=lambda a,b:a*b
print(product(5,6))

ALLA SUSHMA(MCA)
PYTHON TRAINER
Example:functions that take other functions as their arguments
def testfun(num):
return lambda x:x*num
result1=testfun(10)
print(result1(9))

Example-4:
def testfun(num):
return lambda x:x*num
result1=testfun(10)
result2=testfun(1000)
print(result1(9))
print(result2(9))

lambda functions can be used with built-in functions like map() and filter()
filter():
this function returns a list of those elements that the return ‘true’ when evaluated by the
lambda function.
Example:
number_list=[45,1,2,89,56,3,4,9,10]
filter_list=list(filter(lambda num:(num>7),number_list))
print(filter_list)

map():
● This function can be dictionary , a list……………..
● This function basically maps every item in the input iterable to the corresponding
item in the output iterable according to the logic defined by the lambda function.
Example:
number_list=[26,57,45,66,234,567,890,12]
map_list=list(map(lambda num:(num%2),number_list))
print(map_list)

Example:invoking one user defined function to another function


ALLA SUSHMA(MCA)
PYTHON TRAINER
def cube(x):
return(x*x*x)
def sum_cube(array,n):
sum=0
for i in range(n):
cubevalue=cube(array[i])
sum=sum+cubevalue
return sum
array=[2,3,4,5,6,7]
n=len(array)
tot=sum_cube(array,n)
print("sum of cube:",tot)

pre-defined functions

MATHEMATICAL functions:
Number functions:
1.ceil():this function returns smallest integral value greater than the number . if number is
already integer same number is returned.
2.floor():it returns greatest integral value smaller than the number is returned.
Example:
>>> import math
>>> a=6.789
>>> print(math.ceil(a))
7
>>> print(math.floor(a))
6

3.fabs():it returns absolute value of the number.


4.factorial():it returns the factorial of a given number.
Example:
>>> import math
>>> a=-34
>>> b=7
>>> print(math.fabs(a))
34.0
>>> print(math.factorial(b))
5040
ALLA SUSHMA(MCA)
PYTHON TRAINER
5.copysign(a,b):it returns the number with value of “a” but the sign of “b” , the return value is
float type.
6.gcd():it is used to compute the greatest common divisor of 2 number mentioned in its
arguments.
Example:
>>> import math
>>> print(math.copysign(4.5,-10))
-4.5
>>> print(math.copysign(-4.5,10))
4.5
>>> print(math.copysign(-4.5,-2.3))
-4.5
>>> print(math.gcd(23,78))
1

Logarithmic and power functions:


1.exp(a):it returns the value is raised to the power (e**a)
2.log(a,b):it returns the logarithmic value of “a” with base “b”, if base “b” is not mentioned
the computated value is of natural log.
Example:
>>> import math
>>> print(math.exp(67))
1.2523631708422137e+29
>>> print(math.log(23,12))
1.26181569685793

3.log2(a):it computes values of log “a” with base “2”


4.log10(a): it computes log “a” with base “10”
Example:
>>> import math
>>> print(math.log2(12))
3.584962500721156
>>> print(math.log10(34))
1.5314789170422551
>>> print(math.log2(-34))
ValueError: math domain error
>>> print(math.log10(34.567))
ALLA SUSHMA(MCA)
PYTHON TRAINER
1.5386616896384038

5.pow(a,b):it is used to compute value of “a” raised to the power “b” (a**b)
6.sqrt(): it returns the square root of the number
Example:
>>> import math
>>> print(math.pow(3,4))
81.0
>>> print(math.sqrt(34))
5.830951894845301
>>> print(math.sqrt(67.89))
8.239538822045807
>>> print(math.sqrt(-23))#value error

Trigonometric and angular functions:


1.sin(): it returns the sin of value passed as argument. The value passed in this function
should be in radians.
2.cos(): it returns the cosine of value passed as argument.
Example:
>>> import math
>>> a=math.pi/6
>>> print(math.sin(a))
0.49999999999999994
>>> print(math.cos(a))
0.8660254037844387

3.tan():it returns the tangent of value passed in arguments.


4.hypot(a,b):it returns the hypotenuse of the values passed in arguments . It returns the value
of sqrt(a*a+b*b).
Example:
>>> import math
>>> a=math.pi/6
>>> b=6
>>> c=5
>>> print(math.tan(a))
0.5773502691896257
>>> print(math.hypot(b,c))
7.810249675906654

ALLA SUSHMA(MCA)
PYTHON TRAINER
5.degrees(): it is used to convert argument value from radians to degree.
6.radians():it is used to convert argument value from degree to radians.
Example:
>>> import math
>>> a=math.pi/6
>>> b=30
>>> print(math.degrees(a))
29.999999999999996
>>> print(math.radians(b))
0.5235987755982988

Special functions and constants:


1.gamma(): it is used to return the gamma function of the arguments.
Example:
>>> import math
>>> a=10
>>> print(math.gamma(a))
362880.0
2.pi:this is an in built constant that outputs the value pi(3.141).
3.e:it is an built in constant that output the value of e(2.718281).
Example:
>>> import math
>>> print(math.pi)
3.141592653589793
>>> print(math.e)
2.718281828459045

Type conversion functions:


1.int(a,base): it converts any datatype to integer. “base” specifies the base in which string is
data type is string.
2.float():it is used to convert any datatype to floating point number.
Example:
>>> s="10010"
>>> c=int(s,2)
>>> print(c)
18
>>> e=float(s)
>>> print(e)
10010.0
ALLA SUSHMA(MCA)
PYTHON TRAINER
>>> e=34
>>> s=float(e)
>>> print(s)
34.0

3.ord():it used to convert character to string.


4.hex(): it converts integer to hexadecimal string
5.oct():this function is to convert integer to octal string
Example:
>>> s="4"
>>> c=ord(s)
>>> print(c)
52
>>> c=hex(56)
>>> print(c)
0x38
>>> c=oct(78)
>>> print(c)
0o116

6.tuple():it is used to convert a tuple.


7.set():it returns the type after converting to set.
8.list():it is used to convert any data type to a list type.
Example:
>>> s="sushma"
>>> c=tuple(s)
>>> print(c)
('s', 'u', 's', 'h', 'm', 'a')
>>> c=set(s)
>>> print(c)
{'h', 'u', 'm', 's', 'a'}
>>> c=list(s)
>>> print(c)
['s', 'u', 's', 'h', 'm', 'a']

9.dict():it is used to convert tuple of order(key,value) into a dictionary.


10.str():it is used to convert integer into a string.
11.complex(real,img):it converts real numbers to complex(real ,imag) number.
Example:
ALLA SUSHMA(MCA)
PYTHON TRAINER
>>> tuple=(('a',1),('b',2),('c',3))
>>> c=dict(tuple)
>>> print(c)
{'a': 1, 'b': 2, 'c': 3}
>>> a=5
>>> b=4
>>> c=complex(a,b)
>>> print(c)
(5+4j)
>>> s=45
>>> c=str(s)
>>> print(c)
45
>>> print(type(c))
<class 'str'>

TUPLES
A tuple is a sequence of immutable objects, therefore tuple cannot be changed.
Tuples are similar to list. Tuples are represented with in paranthesis(‘()’).
Tuples support positive indexing and negative indexing.
Example:
>>> data1=(10,20,30,40)
>>> print(data1[2])
30
>>> print(data1[0:2])#by using slice operator(:)
(10, 20)
>>> print(data1[:5])
(10, 20, 30, 40)
>>> print(data1[1:])
(20, 30, 40)
>>> print(data1[-3:-1])
(20, 30)
>>> print(data1[-1:-4])
()

Tuple operations:
1.Adding tuple: it can be added by using the concatenation operator(+) to join two tuples.
Example:
>>> data1=(23,34,45,56)
ALLA SUSHMA(MCA)
PYTHON TRAINER
>>> data2=(78,89,98)
>>> data1+data2
(23, 34, 45, 56, 78, 89, 98)

2.replicating tuple: it can be performed by using “*” operator by a specific number of times.
Example:
>>> data1=(20,30,40)
>>> data1*3
(20, 30, 40, 20, 30, 40, 20, 30, 40)

1.updating elements in a tuple:


Elements of the tuple cannot be updated.
Example:
>>> data=('s','m','y')
>>> data[1]='a'
TypeError: 'tuple' object does not support item assignment

Deleting a tuple:
Deleting individual element from a tuple is not supported.
Example:
>>> data=('s','m','y')
>>> del data
>>> print(data)

Functions in tuple:
1.min(tuple):returns the minimum value in the tuple.
Example:
>>> data1=(34,12,1,67,89,123)
>>> print(min(data1))
1
2.max(tuple):returns the maximum value in the tuple.
Example:
>>> data1=(67,123,789,23,1,90,897)
>>> print(max(data1))
897
3.tuple(Sequence): converts the sequence into tuple.
Example:
>>> data=['mani','sushma','chanti','anil']
ALLA SUSHMA(MCA)
PYTHON TRAINER
>>> data1=tuple(data)
>>> print(data1)
('mani', 'sushma', 'chanti', 'anil')

Uses of tuples:
1.tuples are faster than list
2.it makes data safe as tuples are immutable and hence cannot be changed.
3.tuples are used for string formatting.

Interview question:
What is the difference between arrays and lists?
Arrays LISTS
It is collection of homogeneous data It is collection of heterogeneous data.
Not a native data type(need an import) Native data type(no need to import)
Arithmetic operations are element-wise Arithmetic operations are not element-wise
Uses memory efficiency Not efficient in memory usage
Performance is fast Slower performance
A loop has to be formed to print or access the The entire list can be printed with out any
components of a array. explicit looping
Adding elements to an numpy array creates a Elements can be added to a list without
new array and destroy the old one creating a whole new list.

Interview question:
What is the difference between list and tuple?
tuple List
It is represented in paranthesis ‘()’ It is represented in ‘[]’.
Tuples are immutable(not modifiable) Lists are mutable(modifiable)
There are 33 available methods on tuples There are 46 available methods on lists
In dictionary, we can create keys using tuples In dictionary, we can’t use lists as keys

DICTIONARY
● It is an unordered set of key and value pairs.
● It is an container that contains data , enclosed within curly braces(‘{}’).
● The pair i.e key and value is known as ‘item’.
● The key passed in the item must be unique.
● It is known as associative array.
● It is mutable(modify) values can be updated.
● Values can be updated while key cannot be changed.

ALLA SUSHMA(MCA)
PYTHON TRAINER
Example:
>>> name={}
>>> name[1]='sushma'
>>> name[2]='manikumar'
>>> name['name1']='sowmya'
>>> name[4]='anil'
>>> print(name[2])
manikumar
>>> print(name[1])
sushma
>>> print(name)
{1: 'sushma', 2: 'manikumar', 'name1': 'sowmya', 4: 'anil'}

Assigning values to the dictionary:


A dictionary value can be assigned by their keys.
Syntax:
[key]
Example:
>>> data1={'id':101,'name':'sushma','desg':'software'}
>>> data2={'id':102,'name':'manikumar','desg':'business'}
>>> data1['name']
'sushma'
>>> data2['desg']
'business'
>>> data1['id']
101

Updation:
The item i.e key-value pair can be updated. Updating means new item can be added. The
values can be modified.
Example:
>>> data1={'id':101,'name':'sushma','desg':'software'}
>>> data2={'id':102,'name':'manikumar','desg':'business'}
>>> data1['desg']='python trainer'
>>> print(data1)
{'id': 101, 'name': 'sushma', 'desg': 'python trainer'}
>>> data2['salary']=60000
>>> print(data2)
{'id': 102, 'name': 'manikumar', 'desg': 'business', 'salary': 60000}
ALLA SUSHMA(MCA)
PYTHON TRAINER
Deletion:
Del statement is used for performing deletion operation.
Syntax:
del[key]
Example:
>>> data1={'id':101,'name':'sushma','desg':'software'}
>>> del data1['desg']
>>> print(data1)
{'id': 101, 'name': 'sushma'}

Functions:
1.len(dictionary):gives number of items in the dictionary.
Example:
>>> data1={'id':101,'name':'sushma','desg':'software'}
>>> print(len(data1))
3
2.str(dictionary): gives string representation of dictionary.
Example:
>>> data1={'id':101,'name':'sushma','desg':'software'}
>>> data2=str(data1)
>>> print(data2)
{'id': 101, 'name': 'sushma', 'desg': 'software'}
>>> type(data2)
<class 'str'>
>>>
Methods:
1.keys():
Returns all the keys elements in a dictionary.
Example:
>>> data1={100:'sushma',101:'manikumar',103:'anil'}
>> print(data1.keys())
dict_keys([100, 101, 103])

2.values():
Return all the values elements of a dictionary
Example:
>>> data1={'id':345,'name':'mani','desg':'software trainer'}
>>> print(data1.values())
ALLA SUSHMA(MCA)
PYTHON TRAINER
dict_values([345, 'mani', 'software trainer'])

3.items(): return all the key-value pairs of a dictionary.


Example:
>>> data1={'id':345,'name':'mani','desg':'software trainer'}
>>> print(data1.items())
dict_items([('id', 345), ('name', 'mani'), ('desg', 'software trainer')])

4.update(dictionary): it is used to add items of the existing dictionary


Example:
>>> data1={'id':345,'name':'mani','desg':'software trainer'}
>>> data2={'salary':90000}
>>> data1.update(data2)
>>> print(data1)
{'id': 345, 'name': 'mani', 'desg': 'software trainer', 'salary': 90000}

5.clear(): it is used to remove all the items in the dictionary.


Example:
>>> data1={'id':345,'name':'mani','desg':'software trainer'}
>>> data1.clear()
>>> print(data1)
{}

6.fromkeys(sequence,value)/fromkeys(sequence): it is used to create a dictionary from the


sequence where sequence elements from the key and all keys share the values .
in case value is not given it sets the values of keys to be none.
Example:
>>> sequence=('id','name','email')
>>> data={}
>>> data=data.fromkeys(sequence)
>>> print(data)
{'id': None, 'name': None, 'email': None}
>>> data=data.fromkeys(sequence,23)
>>> print(data)
{'id': 23, 'name': 23, 'email': 23}
>>> data=data.fromkeys(sequence,45,56,67)
TypeError: fromkeys expected at most 2 arguments, got 4

7.copy(): it returns an ordered copy of the data.


ALLA SUSHMA(MCA)
PYTHON TRAINER
Exmple:
>>> data1={100:'sushma',200:'mani',300:'anil'}
>>> data2=data1.copy()
>>> print(data2)
{100: 'sushma', 200: 'mani', 300: 'anil'}

8.has_keys(key): it returns a Boolean value. True in case if any key is present in the dictionary,
else false .
Example:
>>> data1={100:'sushma',200:'sowmya',300:'rachana'}
>>> print(data1.has_keys(200))
AttributeError: 'dict' object has no attribute 'has_keys'

9.get(key): returns the values of the given key . if key is not present it returns none.
Example:
>>> data1={100:'sushma',200:'sowmya',300:'rachana'}
>>> print(data1.get(300))
rachana
>>> print(data1.get('name'))
None

SETS
It is an unordered collection of items, sets are mutable(modifiable). Sets will not store
duplicate elements. Sets are created by placing all the elements inside the curly braces({}).
Set will not follow any order.
Example:
>>> set1={1,2,3}
>>> print(set1)
{1, 2, 3}
>>> set2={12.34,"anil",(1,2,3)}
>>> print(set2)
{'anil', 12.34, (1, 2, 3)}
>>> set3=set([4,5,6])
>>> print(set3)
{4, 5, 6}

Example-2:
>>> a={}
>>> print(type(a))
ALLA SUSHMA(MCA)
PYTHON TRAINER
<class 'dict'>
>>> a=set()
>>> print(type(a))
<class 'set'>

Methods:
1.add():it add single element in the set.
Example:
>>> set={1,2,3}
>>> set.add(5)
>>> print(set)
{1, 2, 3, 5}

2.update(): this method can take tuples, lists, strings or sets as its arguments.
Example:
>>> set1={45,67,78}
>>> set1.update([23,34,12])
>>> print(set1)
{34, 67, 12, 45, 78, 23}

3.union(): it returns a union of two sets . using or operator between two sets is the same as
writing set1.union(set2).
Example:
>>> names={"sushma","mani","chanti"}
>>> desg={"training","business","testing"}
>>> employee=names.union(desg);
>>> print(employee)
{'sushma', 'chanti', 'business', 'testing', 'mani', 'training'}

Frozen Set:
These are also immutable objects that only support methods and operators that produce a
result without effecting the frozenset or sets to which they are applied.
Example:
>>> set1=set(['a','b','c','d'])
ALLA SUSHMA(MCA)
PYTHON TRAINER
>>> set1.add('e')
>>> print("normal set")
normal set
>>> print(set1)
{'d', 'a', 'b', 'e', 'c'}
>>> set2=frozenset(['f','g','h'])
>>> print(set2)
frozenset({'g', 'h', 'f'})

operators using in the frozen set:


1.key in s(#containment check)
2.key not in s(non-containment check)
3.s1==s2(s1 is equivalent to s2)
4.s1!=s2(s1 is not equivalent to s2)
5.relational operators
● Case-1:s1 is subset of s2(s1<s2)
● Case-2:s1 is proper superset of s2(s1>=s2)
● Case-3:s1 is proper subset of s2(s1<=s2)
● Case-4:s1 is superset of s2(s1>s2)
6.s1|s2(the union of s1 and s2)
7.s1&s2(the intersection of s1&s2)
8.s1-s2(the sets of elements in s1 but not in s2)
9.s1^s2(the set of elements in precisely one of s1 or s2)

Example:
set1=set()
set2=set()
for i in range(1,6):
set1.add(i)
for i in range(3,8):
set2.add(i)
print("set1=",set1)
print("set2=",set2)
print("\n")
set3=set1|set2
print("union of set1 and s2:set3=",set3)
set4=set1&set2
print("intersection of set1&set2:set4=",set4)
if set3>set4:
ALLA SUSHMA(MCA)
PYTHON TRAINER
print("set3 is superset of set4")
elif set3<set4:
print("set3 is subset of set4")
else:
print("set3 is same as set4")
if set4<set3:
print("set4 is subset of set3")
print("\n")
set5=set3-set4
print("elements in set3 and not in set4:set5=",set5)
print("\n")
if set4.isdisjoint(set5):
print("set4 and set5 have nothing in common\n")
set5.clear()
print("after applying clear on set5:")
print("set5=",set5)

Python Date and Time


It helps to retrieve current date and manipulation using buit in methods.
Methods:
Retrieving time:
To retrieve time, python provides pre-defined function localtime(). It receives a parameter
time. time() is a function that returns the current system time in number of ticks since 12:00
am, January 1st 1970.
time() function 9 attributes:
Attributes Description
tm_year It returns the current year
tm_mon It returns current month
tm_mday It returns the current month day
tm_hour It returns the current hour
tm_min It returns current minute
tm_sec It returns current seconds
tm_wday It returns week day
tm_yday It returns the year day
tm_isdst It returns -1,0 or 1

Example:
>>> import time
>>> localtime=time.localtime(time.time())

ALLA SUSHMA(MCA)
PYTHON TRAINER
>>> print(localtime)
time.struct_time(tm_year=2020, tm_mon=12, tm_mday=19, tm_hour=12, tm_min=4,
tm_sec=53, tm_wday=5, tm_yday=354, tm_isdst=0)

formatted time in python:


it uses pre-defined function like asctime(). This function returns formatted time which
includes day,month, date, time and year. It returns 24 character as string.
Example:
>>> import time
>>> localtime=time.asctime(time.localtime(time.time()))
>>> print(localtime)
Sat Dec 19 12:08:54 2020

strptime(String str,format f) method:


It returns tuples with 9 time attributes. It receives an string of data and time format.
Attribute Description
%a Weekday name
%b Month name
%c Date and time
%e Day of the month
%m Month in digit
%n New line character
%S Second
%t Tab character
%d Day of the month
%y Year
%h Hours
%M Minute

Example:
>>> import time
>>> timerequired=time.strptime("26 jun 14","%d %b %y")
>>> print(timerequired)
time.struct_time(tm_year=2014, tm_mon=6, tm_mday=26, tm_hour=0, tm_min=0, tm_sec=0,
tm_wday=3, tm_yday=177, tm_isdst=-1)

python calendar Module


Methods Description
prcal(year) It prints the hole calendar of the year
ALLA SUSHMA(MCA)
PYTHON TRAINER
firstweekday() It returns the first week day . it is by default 0
which specifies Monday.
isleap(year) It returns Boolean true . true in case year is
leap otherwise false
monthcalendar(year,month) It returns the given month with each week as
a list
prmonth(year,month) It prints the given month of the given year

Example:
>>> import calendar
>>> calendar.prcal(2020)

Example-2:
>>> import calendar
>>> print(calendar.firstweekday())
0

Example-3:
>>> import calendar
>>> print(calendar.isleap(2015))
False
>>> print(calendar.isleap(2016))
True

Example-4:
>>> import calendar
>>> print(calendar.monthcalendar(2020,8))
[[0, 0, 0, 0, 0, 1, 2], [3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16], [17, 18, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 29, 30], [31, 0, 0, 0, 0, 0, 0]]
>>>

Example-5:
>>> import calendar
>>> print(calendar.prmonth(2020,9))
September 2020
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20

ALLA SUSHMA(MCA)
PYTHON TRAINER
21 22 23 24 25 26 27
28 29 30

Oops concepts in python


Major principles of object oriented programming system are given below:
● Classes and objects
● Encapsulation
● Abstraction
● Inheritance
● Polymorphism

Object:
An object is instance of class.
(or)
An object is anything that exists physically in the real world. It contains variables and
methods.

Class:
A class is a blue print.
(or)
A class is a model or plan for creating objects.
(or)
A class represents common behavior of group of objects.
(or)
A class which doenot exist physically in the real world.

Example:
Cars(class)
Audi
Benz
Innova
Tata

Syntax:
class class_name:
<statements>
……….

ALLA SUSHMA(MCA)
PYTHON TRAINER
………..
<statements-n>
Object_name=class_name()

Example:
class person:#class
def name(self):#method
print("this is sushma")
def company(self):
print("magneq software")
p=person()#'p' is object to the person class
p.name()#by using 'p' object we can call the methods present in the class
p.company()

Method:
It is a function that is associated with an object . in python, method is not unique to class
instance. Any object type can have methods.

Inheritance:
Creating a new class from already existing class is called inheritance.
Code reusability is main advantage of inheritance.

Polymorphism:
Poly means many and morphism means forms . it is derived from latin and greek words.
The ability to exists in many forms is called polymorphism .
In programming if the same method or variable or object performs various tasks is called
polymorphism.

Encapsulation:
Taking data and methods into single unit is called encapsulation.
A class is an example for encapsulation
The main advantage of encapsulation is that it is possible to use same names for the members
of two different class.

Abstraction:
It means hiding of data.
ALLA SUSHMA(MCA)
PYTHON TRAINER
Hiding unnecessary data from the user is called abstraction.
It is used to hide internal details and show only functionalities.

class method:
it receives the class as implicit first argument, just like an instance method receives the
instance.
Syntax:
class c(object):
@classmethod
def fun_name(cls,arg1,arg2……………………..)
………………
…………………

🡪A class method is a method which is bound to the class and not the object of the class.
🡪They have the access to the state of the class as it takes as class parameter that points to the
class and not the object instance.
🡪it can modify a class state that would apply across all the instances of the class.
🡪if you want to call class method, we can call with object_name.method_name

Static method:
It does not receive an implicit first argument.
Syntax:
class c(object):
@staticmethod
def fun(arg1,arg2…………..):
------------------
-----------------
🡪it cannot access or modify class.
🡪it is present in a class because it makes sense for the method to be present in the class.
🡪by using static method you need not create object to the class name but we can call
class_name.method name() (or) object_name.method_name()
Example:
from datetime import date
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
@classmethod
def frombirthyear(cls,name,year):
ALLA SUSHMA(MCA)
PYTHON TRAINER
return cls(name,date.today().year-year)
@staticmethod#not need of creating object to the class name
def isadult(age):
return age>18
person1=Person('sushma',27)
person2=Person.frombirthyear('sushma',1990)
print(person1.age)
print(person2.age)
print(Person.isadult(22))
print(Person.isadult(17))

what is the difference between class method and static method?


Class Method Static Method
1.it take class as first parameter 1.no specific parameter
2.it can access or modify class state 2.it can’t access or modify it
3.we use @classmethod decorator in python 3.we can use @staticmethod decorator to
to create class method create static method
4.we can use class method to create factory 4.we generally use static methods to create
methods . factory method return class utility functions.
object(similar to a constructor) for different
use cases

Constructors

● A constructor is a special type of method that is called instantiates an object using


definition found in the class. It is normally used to initialize instance variables.
● A class function that begins with double underscore(__). The name of the constructor
is always same __init__().
● While creating object a constructor can accept arguments if necessary.
● Constructor should not return any value.
● Constructor always represented with ‘public’
There are two types of constructors
1.default constructors:
A constructor without parameter is called default constructor or zero-parameterized
constructor. But every object is initialized with same data.
Syntax:
class class_name:
def __init__(self):
statements

ALLA SUSHMA(MCA)
PYTHON TRAINER
Example:
class person:
def __init__(self):#default constructor
self.name="sushma"
self.desg="trainer"
def display(self):#method
print("emp name:",self.name)
print("emp desg:",self.desg)
p=person()
p.display()

p1=person()
p1.display()
2.parameterized constructor:
A constructor with parameters is called parameterized constructor. Here, every object is
initialized with different data.
Syntax:
class class_name:
def __init__(self,par1,par2………..):
statements
Example:
class person:
def __init__(self,name,desg):#parametrized constructor
self.name=name
self.desg=desg
def display(self):#method
print("emp name:",self.name)
print("emp desg:",self.desg)
p=person("sushma","trainer")
p.display()

p1=person("mani","business")
p1.display()

class variables or static variables in python:


these variables are shared by all objects . instance or non-static variables are different for
different objects.
🡪All variables which are assigned a value in class declaration are class variables.
🡪variables which are assigned values inside class methods are instance methods.
ALLA SUSHMA(MCA)
PYTHON TRAINER
Example:
class Student:
branch='MCA'#class variable
def __init__(self,name,roll):
self.name=name
self.roll=roll
a=Student('sushma',90)
b=Student('mani',96)
print(a.branch)
print(b.branch)
print(a.name)
print(b.name)
print(a.roll)
print(b.roll)
print(Student.branch)

Access modifiers in python:


Access modifiers play an important role to protect the data from unauthortized access as
well as protecting it from getting manipulated .
There are 3 types:
1.public:
● Public members are accessible from outside the class through an object of the
class.
● By default, all the variables are member functions of a class are ‘public’ in a
python.

Example:
class Employee:
def __init__(self,name,sal):
self.name=name#public variables
self.sal=sal
emp=Employee("sushma",90000)
print(emp.sal)
print(emp.name)

2.protected:
● Protected members are accessible from outside the class but only in a class derived
from it is called child class.
ALLA SUSHMA(MCA)
PYTHON TRAINER
● Adding a prefix _(single underscore) to a variable name makes it protected.
Example:
class Employee:
def __init__(self,name,age):
self._name=name#protected variables
self._age=age
class HR(Employee):
def task(self):
print("assiging work to employess")
emp=Employee("sushma",27)
print(emp._name)
print(emp._age)
ehr=HR("mani",34)
print(ehr._name)
print(ehr._age)
ehr.task()

3.private:
These members are only accessible from within the class. No outside of class is allowed.
While the addition of prefix __(double underscore) results in a member variable or function
becoming private.
Example:
class Employee:
def __init__(self,name,age):
self.__name=name#private variables
self.__age=age

emp=Employee("sushma",27)
print(emp.__name)
print(emp.__age)

str() and repr()


🡪both are used to get a string representation of object.
Example:
>>> s="sushma"
>>> print(str(s))
ALLA SUSHMA(MCA)
PYTHON TRAINER
sushma
>>> print(str(23.45/67.89))
0.3454116953896008
>>> s="sushma"
>>> print(repr(s))
'sushma'
>>> print(repr(23.45/12.34))
1.9003241491085898

Interview question:
What is the difference between str() and repr():
str() repr()
It is used for creating output for end user It is used for debugging and development
‘str’ is to be readable ‘repr’ goal is to be ‘unambiguous.
It is used to compute the ‘informal’ string It compute the ‘official’ string representation
representation of an object. of an object
The print statement and str() buit in function repr() built in function uses __repr__ to
uses __str__ to display the string display the object.
representation of the object

Example:
>>> import datetime
>>> today=datetime.datetime.now()
>>> print(str(today))
2020-12-24 11:05:28.233740
>>> print(repr(today))
datetime.datetime(2020, 12, 24, 11, 5, 28, 233740)

note:
🡪str() displays today’s date in a way that the user can understand the date and time.
🡪repr() prints official representation of a datetime object.

How to make them work for our own defined classes:


Example:
class complex:
def __init__(self,real,imag):
self.real=real
self.imag=imag
def __repr__(self):

ALLA SUSHMA(MCA)
PYTHON TRAINER
return 'rational(%s,%s)'%(self.real,self.imag)
def __str__(self):
return '%s+i%s'%(self.real,self.imag)
t=complex(10,20)
print(str(t))
print(repr(t))

DECORATORS
In python, functions are first class objects.
🡪functions are objects, they can be referenced to , passed to a variable and returned from
other function as well.
🡪function can be defined inside another function and can also be passed as argument to
another function.
Definition of decorator:
🡪it is very powerful tool in python.
🡪it allows programmers to modify the behavior of functions and classes.
🡪it allows us to wrap another function in order to extend the behavior of wrapped function
without permanently modifying it.
🡪here, functions are taken as the arguments into another function and then called inside the
wrapper function.
Example:
@gfg_decorator#warpped function
def h_decorator():
print(‘gfg’)

note:
🡪gfg_decorator is a callable function , will add some code on the top of another callable
function
🡪h_decorator can return the wrapper function

Example:
Find out execution time of function using decorator
import time
import math
def cal_time(func):
def inner(*args,**kwargs):
begin=time.time()
func(*args,**kwargs)
end=time.time()
ALLA SUSHMA(MCA)
PYTHON TRAINER
print("time taken:",func.__name__,end-begin)
return inner
@cal_time
def fact(num):
time.sleep(4)
print(math.factorial(num))
fact(9)

Example:
function returning values
def h_dec(func):#step-1
def inner(*args,**kwargs):#step-2
print("before execution")
returned_value=func(*args,**kwargs)
print("after execution")#step-4
return returned_value
return inner
@h_dec
def sum(a,b):#step-3
print("inside the function")
return a+b#step-5
a,b=56,67
print("sum=",sum(a,b))#step-6

Example-3:
def attach_data(func):
func.data=3
return func
@attach_data
def add(x,y):
return x+y
print(add(78,89))
print(add.data)

class Attributes:
it belongs to the class itself they will be shared by all the instances . such attributes are
defined in the class body statements usually at the top, for eligibility.
Example:
class sampleclass:
ALLA SUSHMA(MCA)
PYTHON TRAINER
count=0#class attribute
def increase(self):
sampleclass.count+=1
s1=sampleclass()
s1.increase()
print(s1.count)#1
s2=sampleclass()
s2.increase()
print(s2.count)#2
print(sampleclass.count)#2

instance attributes:
🡪these are not shared by objects.
🡪every object has its own copy of the instance attributes.
Attributes:
1.vars():
It displays the attribute of an instance in the form of an dictionary.
2.dir():
It displays more attributes than various functions, as it is not limited to instead to instances. It
displays the class attributes as well.
Example:
class stu:
def __init__(self):
self.name='manikumar'
self.branch='CSE'
def display(self):
print(self.name)
print(self.branch)
s1=stu()
print("dictionary form:",vars(s1))
print(dir(s1))

INHERITANCE
🡪the method of inheriting the properties of parent class into a child class is known as
inheritance.
🡪code reusability is the main advantage of inheritance.
🡪it is transitive in nature. If a child class inherits properties from a parent class, then all other
sub-class of the child class will also inherit the properties of the parent class.
ALLA SUSHMA(MCA)
PYTHON TRAINER
Syntax:
class super_classname:
statements
class sub_classname(super_classname):
statements

types of inheritances:
1.single inheritance:
It enables a derived class to inherit properties from single parent class.

Example:
class Parent:
def display(self):
print("it is parent class")

class child(Parent):
def display1(self):
print("it is child class")
c=child()
c.display()
c.display1()

multilevel inheritance:
you can inherit a derived class from another derived class.

Example:
ALLA SUSHMA(MCA)
PYTHON TRAINER
class person:#parent class
def display(self):
print("hello this is a class person")
class employee(person):#intermediatory class
def printing(self):
print("hello this is derived class")
class programmer(employee):#child class
def show(self):
print("hello this is another derived class")
p1=programmer()
p1.display()
p1.printing()
p1.show()

multiple inheritance:
deriving a child class from more than one base class is called multiple inheritance.

Example:
class land_animal:#super class
def printing(self):
print("this animal lives on land")
class water_animal:#super class
def display(self):
print("this animal lives in water")
class frog(land_animal,water_animal):#sub class
ALLA SUSHMA(MCA)
PYTHON TRAINER
pass
f1=frog()
f1.printing()
f1.display()

hierarchical inheritance:
it involves multiple inheritance from the same base or parent class

Example:
class Details:#super class
def __init__(self):
self.__id="<no id>"
self.__name="<no name>"
self.__gender="<no gender>"
def setData(self,id,name,gender):
self.__id=id
self.__name=name
self.__gender=gender
def showData(self):
print("ID:",self.__id)
print("NAME:",self.__name)
print("GENDER:",self.__gender)

class Employee(Details):#sub class1


def __init__(self):
self.__company="<no company>"
self.__dept="<no dept>"
def setEmployee(self,id,name,gender,comp,dept):
self.setData(id,name,gender)
self.__company=comp
self.__dept=dept
def showEmployee(self):
self.showData()
print("COMPANY:",self.__company)
ALLA SUSHMA(MCA)
PYTHON TRAINER
print("DEPARTMENT:",self.__dept)
class Doctor(Details):#sub class 2
def __init__(self):
self.__hospital="<no hospital>"
self.__dept="<no dept>"
def setEmployee(self,id,name,gender,hos,dept):
self.setData(id,name,gender)
self.__hospital=hos
self.__dept=dept
def showEmployee(self):
self.showData()
print("HOSPITAL:",self.__hospital)
print("DEPARTMENT:",self.__dept)

def main():
print("employee object")
e=Employee()
e.setEmployee(1,"sushma","female","reddy labs","excavation")
e.showEmployee()
print("\n doctor object")
d=Doctor()
d.setEmployee(1,"mani","male","aiims","eyes")
d.showEmployee()

if __name__=="__main__":
main()

how we can define private methods in python?


In python, there is no existence of private methods that cannot be accessed except inside a
class. However, to define a private method prefix the member name with double underscore.
Note:
The __init__ method is a constructor and runs as soon as an object of a class is initantiated.

Example:
class Base:
def fun(self):
print("public method")
ALLA SUSHMA(MCA)
PYTHON TRAINER
def __fun(self):#private method
print("private function")
class Derived(Base):
def __init__(self):
Base.__init__(self)
def call_public(self):
print("\n inside derived class")
self.fun()
def call_private(self):
self.__fun()

obj1=Base()
obj1.fun()
obj2=Derived()
obj2.call_public()
obj2.call_private()

polymorphism
🡪polymorphism is taken from the greek words.
🡪it means that the same function name can be used for different types.
Example-1:
Polymorphism with function and objects
class Tomato():
def type(self):
print("vegetable")
def color(self):
print("red")
class Apple():
def type(self):
print("fruit")
def color(self):
print("red")
def func(obj):
obj.type()
obj.color()
obj_tam=Tomato()
ALLA SUSHMA(MCA)
PYTHON TRAINER
obj_app=Apple()
func(obj_tam)
func(obj_app)

Example:-2
Polymorphism with class methods:
class India():
def capital(self):
print("new delhi")
def language(self):
print("eng and hindi")
class USA():
def capital(self):
print("washington")
def language(self):
print("english")
obj_ind=India()
obj_usa=USA()
for country in(obj_ind,obj_usa):
country.capital()
country.language()

method overloading:
writing one or more methods with same name but difference in the arguments is called
method overloading.
Arguments different will be based on a no.of arguments and type of arguments.
It is used in a single class
It is used to write code clarity as well as reduce complexity.
Example:
class Area():
def find_area(self,a=None,b=None):
if a!=None and b!=None:
print("area of rectangle:",(a*b))
elif a!=None:
print("Area of square:",(a*a))
else:
print("nothing to find")

obj1=Area()
ALLA SUSHMA(MCA)
PYTHON TRAINER
obj1.find_area()
obj1.find_area(10)
obj1.find_area(10,20)

method overriding:
writing one or more methods with same name and same parameters is called method
overriding.
It is implemented with inheritance
It is mostly used for memory reducing process.
Example:
class Rectangle():
def __init__(self,length,breath):
self.length=length
self.breath=breath
def getArea(self):
print(self.length*self.breath," is area of rectangle")
class Square(Rectangle):
def __init__(self,side):
self.side=side
Rectangle.__init__(self,side,side)
def getArea(self):
print(self.side*self.side," is area of square")
s=Square(4)
r=Rectangle(2,7)
s.getArea()
r.getArea()

super():
this function is used to give access to methods and properties of a parent or sibling class.
This function returns an object that represents the parent class.
Example:
class Parent:
def __init__(self,txt):
self.message=txt
def printmessage(self):
print(self.message)
class Child(Parent):
def __init__(self,txt):
super().__init__(txt)
ALLA SUSHMA(MCA)
PYTHON TRAINER
x=Child("This is super() function")
x.printmessage()

metaprogramming with meta classes:


🡪in nutshell we can say metaprogramming is code which manipulates code.
Example for metaclasses:
>>> num=345
>>> print(type(num))
<class 'int'>
>>> list=[3,4,5]
>>> print(type(list))
<class 'list'>
>>> name="sushma"
>>> print(type(name))
<class 'str'>

Note:
In python, object of int class or str class, so we can make a new type by creating a class of that
type.

Example:
class student:
pass
stu=student()
print("type of object:",type(stu))

definition of meta class:


A class is also an object , and just like any other object it’s instance of something called
metaclass.
🡪A special class ‘type’ create these class object.
🡪the ‘type’ class is defined default metaclasses which are responsible for making classes.
Example:
class student:
pass
print("type of object:",type(student))

note:

ALLA SUSHMA(MCA)
PYTHON TRAINER
classes are also an object, they can be modified in same way. We can add or subtract fields or
method in class in same way we did it with other.
Example:
class test:
pass
test.x=45
test.foo=lambda self:print("hello")
obj=test()
print(obj.x)
obj.foo()

when we use these metaclasses:


🡪it propogate down the inheritance hierarchies.
🡪if we want to changes classes automatically.
🡪it is used for API(Application programming interfaces) developers

Custom metaclasses:
🡪custom meta classes have to inherit type metaclasses and usually override.
● __new__():this methods which is called before __init__().it creates the object and
return it.
● __init__():it initialize the created object passed as parameter.
🡪we can create classes using type() function directly in following ways:
● When called with only one argument, it returns the type. We have seen it before in
above examples.
● When called with 3 parameters, it creates a class. Following arguments are passed to
it.
🡪class name
🡪tuple having base classes inherited by class
🡪class dictionary
Example:
def t_method(self):
print("test class method")
class Base:
def myfun(self):
print("inherited method")
ALLA SUSHMA(MCA)
PYTHON TRAINER
Test=type('Test',(Base,),dict(x="sushma",my_method=t_method))
print("type of test class:",type(Test))
test_obj=Test()
print("type of test_obj:",type(test_obj))
test_obj.myfun()
test_obj.my_method()
print(test_obj.x)

DOC strings:
It provide a convenient way of associating documentation with modules, functions, classes
and methods.
Rules:
● The docstring lines should begin with a capital letter and end with a period.
● The first line should be a short description .
● If there are more lines in the documentation strings, the second line should be blank,
visually separating the summary from the rest of the description.
🡪docstrings are declared using “”” triple quotation marks”””. All functions should have a doc
strings.
🡪docstrings can be accessed using __doc__ method of the object using help() function.
Example:
def my_function():
"""docstrings does nothing really"""
return None
print(my_function.__doc__)
help(my_function())

one-line doc strings:


these doc strings are fit in one line. The closing quotes are on the same line as the opening
quotes. This looks better for one-line.
Example:
def pow(a,b):
"""returns arg1 raised to power arg2"""
ALLA SUSHMA(MCA)
PYTHON TRAINER
return a**b
print(pow.__doc__)
help(pow(23,2))

multi-line doc-strings:
it consists of a summary line just like one-line docstring. followed by a blank line, followed by
a more collaborate description. The summary line may be on the same line as the opening
quotes or on the next line.
Example:
def my_fun(arg1):
"""
Summary line

extended description of function


parameters:
arg1(int):description of arg1
return :
int:description of return value
"""
return arg1
print(my_fun.__doc__)

docstring using class:


Example:
class ComplexNumber:
"""
This is a class for mathematical operations on complex numbers

Attributes:
real(int):the real part of complex number
imag(int):the imaginary part of complex number
"""
def __init__(self,real,imag):
"""
Constructor created

parameters:
real(int)
imag(int)
ALLA SUSHMA(MCA)
PYTHON TRAINER
"""
def add(self,num):
"""
To add complex numbers

parameters:
num(ComplexNumber):the complex number to be added
return:
CompleNUmber:A comple number which contain sum
"""
re=self.real+num.real
im=self.imag+num.imag
return ComplexNumber(re,im)
help(ComplexNumber)#to access class docstrings
help(ComplexNumber.add)#to access methods docstrings

Encapsulation:
We can restrict access to methods and variables. This prevents data from direct modification
which is called encapsulation.
Example:
class earphone:
def __init__(self):
self.__maxprice=900
def sell(self):
print("selling price:{}".format(self.__maxprice))
def setMaxPrice(self,price):
self.__maxprice=price
e=earphone()
e.sell()
#change the price
e.__maxprice=1000
e.sell()
#using setter method
e.setMaxPrice(1000)
e.sell()

Abstract class
ALLA SUSHMA(MCA)
PYTHON TRAINER
🡪it is considered as a blue print for other classes.
🡪A class contains one or more abstract methods is called an abstract class.
🡪we cannot create an object to abstract class.
🡪it provides the default functionality of the base class.
🡪it defines a common API for a set of sub classes, useful where a third party is providing
plugings in an application.
Syntax:
from abc import ABC#here ABC is a metaclass

Abstract method:
It is a method that has a declaration but does not have an implementation .
(or)
A method without body is called abstract method.
Syntax:
from abc import ABC,abstractmethod
class class_name(ABC):
@abstractmethod
def method_name(self):
pass
Example:
def name(self):
pass

concrete method:
A method with body is called concreate method.
Example:
def name(self):
print(“sushma”)

Note:
Abstract class contains abstract methods and complete methods.

Example:
from abc import ABC,abstractmethod
class shape(ABC):#abstract class
def common(self):
print("this is a concreate method")
@abstractmethod#decorator
def area(self):
ALLA SUSHMA(MCA)
PYTHON TRAINER
pass
@abstractmethod
def perimeter(self):
pass
class square(shape):#sub class for shape class
def __init__(self,side):
self.side=side
def area(self):
return self.side*self.side
def perimeter(self):
return 4*self.side
class Rectangle(shape):#another sub clas for shape class
def __init__(self,length,breath):
self.length=length
self.breath=breath
def area(self):
return self.length*self.breath
def perimeter(self):
return 2*(self.length+self.breath)
s1=square(4)
print(s1.common())
print(s1.area())
print(s1.perimeter())
r1=Rectangle(3,4)
print(r1.common())
print(r1.area())
print(r1.perimeter())

Interfaces
🡪this concept is not explicitly available in python.
🡪An interface is similar to class.
🡪An interface is an abstract class which contain only abstract methods but not a single
concrete method.
Syntax:
from abc import ABC,abstractmethod
class class_name(ABC):#interface
@abstractmethod#decorator
def method_name(self):
ALLA SUSHMA(MCA)
PYTHON TRAINER
pass
rules:
● All methods of an interface is abstract.
● We cannot create object to interface because interface contains abstract methods or
incomplete methods.
● If a class is implementing it has to define all the methods declared in the interface
,the class must be declared abstract.
● If a class is implementing it has to define all the methods given in that interface.
● We use interfaces when all the features needed to be implemented differently for diff
objects.

Example:
from abc import ABC,abstractmethod
class Father(ABC):#interface
@abstractmethod#decorator
def disp1(self):
pass
@abstractmethod
def disp2(self):
pass
class child(Father):#abstract class
def disp1(self):
print("child class")
print("display abstract method called")
def disp2(self):
print("grandchild class")
print("display abstract method-2")
class Granchild(child):#sub class
pass
gc=Granchild()
gc.disp1()
gc.disp2()

what is the difference between abstract class and interface?

● An abstract class can have abstract methods as well as concrete methods, but all
methods of an interface are abstract.

ALLA SUSHMA(MCA)
PYTHON TRAINER
● We use abstract class when there are some common feature shared by all the object
as they are while we use interface if all the features need to be implemented
differently for different object.
● Its programmer job to write child class for abstract class while in interface, any third
party vendor will take responsibility to write child class.
● Interface are slow when compared to abstract class.
● We cannot create object to abstract class and interface why because they contain
incomplete or abstract methods.
● Multiple inheritance is not supported by abstract class.interfaces support multiple
inheritance

MODULES

🡪modules are python files which contain different classes, function, definitions, variable
which we can reuse.
🡪it should always end with a .py extension.
🡪python itself having a vast module library with the default installation
Example:
import math
import calendar
🡪import statement used for module import
🡪we place import statement in top of the python file.
Example:
#finonacci number module
def fib(n):#write fibinacci series up to n
a,b=0,1
while b<n:
print(b),
a,b=b,a+b
def fib2(n):
result=[]
a,b=0,1
while b<n:
result.append(b)
a,b=b,a+b
return result
output:
>>> import fibo
ALLA SUSHMA(MCA)
PYTHON TRAINER
>>> fibo.fib(10)
1
1
2
3
5
8

>>> fibo.fib2(34)
[1, 1, 2, 3, 5, 8, 13, 21]
>>> fibo.__name__
'fibo'
>>>

‘as’ keyword in the module:


Syntax:
import module_name as new_name
call methods of modules using alias name
Example:
>>> import fibo as fibo1
>>> fibo.fib(34)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
fibo.fib(34)
NameError: name 'fibo' is not defined
>>> fibo1.fib(34)
1
1
2
3
5
8
13
21

How to import specific method in module:


Syntax:
from module1 import method1
Example:
ALLA SUSHMA(MCA)
PYTHON TRAINER
>>> from fibo import fib,fib2
>>> fib2(45)
[1, 1, 2, 3, 5, 8, 13, 21, 34]

All functions import a module


Example:
>>> from fibo import *
>>> fib2(67)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Exception handling
Error:
An error is a mistake, misconception or misunderstanding on the part of a software
developer.

Bug:
A bug is the result of a coding error. A bug is the terminology of tester. An error found in the
development environment before the product is shipped to the customer.

Failure:
It is an inability of an software system or component to perform its required functions within
specified performance requirement.

Fault:
An incorrect step, processes or data definition in a computer program that causes the
program to perform in an unintended or unanticipated manner.

Defect:
It can be simply defined as a variance between expected and actual. The defect is an error
found after the application goes into production.

🡪An exception is an event,which occurs during the execution of a program that disrupts the
normal flow of the program instructions.
Types of exceptions:
● Exception
ALLA SUSHMA(MCA)
PYTHON TRAINER
● ArthimeticError
● OverflowError
● ZeroDivisionError
● AssertionError
● ImportError
● IndexError
● KeyError
● IOError
● ValueError
● TypeError
● NameError
🡪if you have some suspicious code that may raise an exception , you can defined you program
by placing the suspicious code in a “try:” block.
🡪After the try block, include “except:” statement, followed by a block of code which handles
the problem as elegantly as possible.

Syntax:
try:
malicious code
except Exception1:
executing the code
except Exception2:
executing the code
……………..
……………..
else:
In case of no exception , execute the else block code.
Example:
>>> 1/0
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
1/0
ZeroDivisionError: division by zero
>>> 'abc'+123
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
ALLA SUSHMA(MCA)
PYTHON TRAINER
'abc'+123
TypeError: can only concatenate str (not "int") to str

Example-1:
x=input("enter number 1:")
y=input("enter number 2:")
z=int(x)/int(y)
print(z)

Example-2:
x=input("enter number 1:")
y=input("enter number 2:")
try:
z=int(x)/int(y)
except Exception as e:
print("exception occured:",e)
print(z)

Example-3:
import sys
randomList=['a',5,2]
for entry in randomList:
try:
print("the entry is",entry)
r=15/int(entry)
break
except:
print("oops!",sys.exc_info()[0],"occured")
print("next entry")
print()
print("the reciprocal of ",entry,"is",r)
output:
the entry is a
oops! <class 'ValueError'> occured
next entry

the entry is 5
the reciprocal of 5 is 3.0

ALLA SUSHMA(MCA)
PYTHON TRAINER
Example-4:
try:
fh=open("text.txt","r")
fh.write("this is my test file for exception handling!!")
except IOError:
print("error:cannot find file or read data")
else:
print("written content in the file successfully")
fh.close()

user-defined Exception in python:


Example:
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""raised when the input value is too large"""
pass
number=10
while True:
try:
i_num=int(input("enter a number:"))
if i_num<number:
raise ValueTooSmallError
elif i_num>number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("this value is too small , try again!!")
print()
except ValueTooLargeError:
print("this value is too larger, try again!!")
print()
print("congratulations! you gussed it correctly")

ALLA SUSHMA(MCA)
PYTHON TRAINER
customized exception classes:
Example:
class SalaryNotInRangeError(Exception):
def __init__(self,salary,message="salary is not in(5000,15000)range"):
self.salary=salary
self.message=message
super().__init__(self.message)
salary=int(input("enter salary amount:"))
if not 5000<salary<15000:
raise SalaryNotInRangeError(salary)

Example-2:
We can also customize the __str__ method itself by overriding it.
class SalaryNotInRangeError(Exception):
def __init__(self,salary,message="salary is not in(5000,15000)range"):
self.salary=salary
self.message=message
super().__init__(self.message)
def __str__(self):
return f'{self.salary}->{self.message}'
salary=int(input("enter salary amount:"))
if not 5000<salary<15000:
raise SalaryNotInRangeError(salary)

NZEC Error:
NZEC means(non zero exit code)
As the name suggests occurs when your code is failed to return ‘ Zero’, it means it is
successfully executed otherwise it will return some other number depending on the type of
the error.
What is the use with NZEC error?
Generally multiple inputs are separated by commas and we read them using input() or
int(input()), but most of the online coding platforms while testing gives input separated by
space and in these cases int(input()) is not able to the input properly and shows an error like
NZEC.

finally:
in case if there is any code which the user want to execute irrespective of the exception.
Syntax:
try:
ALLA SUSHMA(MCA)
PYTHON TRAINER
code
finally:
code which must to be executed

Example-1:
Code-1:the below code works normally and clean up action is taken at the end.
def divide(x,y):
try:
result=x//y
except ZeroDivisionError:
print("sorry!you are dividing by zero")
else:
print("your answer:",result)
finally:
print("finally block")
divide(15,2)

Example-2:
Code raises error and is carefully handled in the except clause
def divide(x,y):
try:
result=x//y
except ZeroDivisionError:
print("sorry!you are dividing by zero")
else:
print("your answer:",result)
finally:
print("finally block")
divide(15,0)

Example-3:
In below code raise error but we don’t have any except clause to handle it. So, clean up action
is taken first and then the error is raised by default by the compiler.
def divide(x,y):
try:
result=x//y
except ZeroDivisionError:
print("sorry!you are dividing by zero")
else:
ALLA SUSHMA(MCA)
PYTHON TRAINER
print("your answer:",result)
finally:
print("finally block")
divide(15,"2")

TKINTER
● It is a standard GUI package to develop desktop applications.
● It is default GUI module.
● It contains set of wrappers that implement the ‘Tk’ widgets as python class.
● It is only a frame work that is built-in into python standard library.
● It is cross-platform, so the same code can easily work on windows,MAC os and linux.
● It is a light weight module
● It is simple to use.

What are Tcl, Tk and Tkinter?


● tkinter is based upon the Tk toolkit, and which are originally designed for the tool
command language(Tcl).
● As Tk is very popular thus it has been ported to a variety of other scripting languages,
including perl(perl/Tk), Ruby(Ruby/tk) and python(tkinter).
● GUI development portability and flexibility of Tk makes it the right tool which can be
used to design and implement a wide variety of commercial –quality GUI applications.

Steps to implement GUI application:


● import the tkinter module
● To create a top-level windowing object that contains your entire GUI application.
● You need to setup all your GUI components and their functionality.
● Then you need to connect these GUI components to the underlying application code.
● Then just enter the main event loop using mainloop()
Example:
import tkinter as tk
win=tk.Tk()#top-level window object is created by Tk class
win.mainloop()

Note:
mainloop() function is a infinite loop which is used to run the application, it will wait for an
event to occur and process the event as long as the window is not closed.

Tkinter windows:

ALLA SUSHMA(MCA)
PYTHON TRAINER
In python “window” refers to a rectangular area some where on the users displays screen
through which can you interact.
Tkinter widgets:
● It refers to the building blocks that make up an application in a graphical user
interface.
● Container: The widgets that lies are Frame,label frame, top-level and paned window.
● Buttons: radio buttons, check buttons and menu buttons
● Text widgets: labels, messages, text
● Entry widgets: scrollbar, listbox, slider, entry(single-line),option menu, text(multiline)
and canvas(vector and pixel graphics).

Frame:
A frame is basically a rectangular area that can contain other widgets. It is used for complex
layouts.
Example:
It you place inside a frame, the frame object is called the parent of the button widget.

Customized window:
● window.title(): it is used to provide the title to the user interface as you can see in
below example.
● geometry(): it contains the width, height and co-ordinates of the top left corner of the
frame.
Syntax:
window.geometry(“widthxheight+xpos+ypos”)

Example:
from tkinter import *
import tkinter as tk

win=tk.Tk()#top-level window object is created by Tk class


win.title("first program")
win.geometry("400x300+30+40")
win.mainloop()

Tk Widgets:
1.Button widget:
● by using this widget we can adjust height and width of button, adding a background
colors to it.

ALLA SUSHMA(MCA)
PYTHON TRAINER
● You can also associate any method or function with a button if you want and then that
method will get called whenever you press the button.
Syntax:
W=Button(master,options)
Master parameter denotes the parent window
Options parameter contain look of the buttons.
Options:
activebackground
bd(width of the border in pixels)
bg(background color)
command(used to set function call)
activeforeground(represents the font color of the button when the mouse hovers the button)
fg(foreground color)
font
height(no of line in the case of text, no of pixels in case of images)
image(image displayed on button)
justify(LEFT, RIGHT, CENTER)
padx(padding of the button in the horizontal direction)
pady(padding of the button in the vertical direction)
width(for textual buttons, it exists as no of letters, in case of images it indicates the pixels).
state(DISABLED to make button unresponsive , ACTIVE represents the active state of the
button)

Example:
import tkinter
win=tkinter.Tk()
win.geometry(“300x300”)
b=tkinter.Button(win,text="submit")
b.pack()
win.mainloop()

2.label widget:
● It is mainly used to provide a message about the other widgets used in python
application to the user.
● You can change (or) update the text inside the label widget anytime you want.
Syntax:
ALLA SUSHMA(MCA)
PYTHON TRAINER
L=Label(master,options)
Example:
import tkinter
from tkinter import *
win=tkinter.Tk()
win.geometry("300x300")
var=StringVar()
label=tkinter.Label(win,textvariable=var,relief=RAISED)
var.set("welcome to magneq software")
label.pack()
win.mainloop()

3.Entry widget:
● It mainly used to display a small text box that the user can type some text info.
● It is only used to get single line text from the user.
Syntax:
E=Entry(master,option=value)
Example:
import tkinter
from tkinter import *
master=Tk()
e=Entry(master)
master.geometry("300x450")
e.pack()
def callback():
print(e.get())
b=Button(master,text='get',width=10,command=callback)
b.pack()
mainloop()

4.Frame widget:
● It is basically a container(an invisible container) whose task is to hold other widgets
and arrange them with respect to each other. It makes up a rectangular region on the
screen.
Syntax:
F=Frame(master,options)
ALLA SUSHMA(MCA)
PYTHON TRAINER
Example:
from tkinter import *
import tkinter
root=tkinter.Tk()
root.geometry("400x400")
w=tkinter.Label(root,text="magneq software",font="80")
w.pack()
f=Frame(root)
f.pack()
b1=Button(f,text="chanti",fg="red")
b1.pack(side=LEFT)
b2=Button(f,text="mani",fg="blue")
b2.pack(side=LEFT)
root.mainloop()

5.CheckButton widget:
It is used to select multiple options or a single option at a time just by clicking the
corresponding to each option.
Syntax:
C=Checkbutton(master,option=value)
Example:
from tkinter import *
import tkinter

def cb():
print("apple is:",var1.get())
print("mango is:",var2.get())
print("grapes is:",var3.get())
win=Tk()
win.geometry("400x300")
f=Frame(relief=RAISED,borderwidth=8)
var1=IntVar()
var2=IntVar()
var3=IntVar()
c1=Checkbutton(f,text="apple",variable=var1,command=(lambda:cb())).pack(side=TOP)
c2=Checkbutton(f,text="mango",variable=var2,command=(lambda:cb())).pack(side=TOP)
c3=Checkbutton(f,text="grapes",variable=var3,command=(lambda:cb())).pack(side=TOP)
f.pack()
mainloop()
ALLA SUSHMA(MCA)
PYTHON TRAINER
6.radio buttons:
It is used for choosing one of ‘n’ possible choices i.e mutually exclusive single choice by giving
each button a unique value of the same tkinter variable.
Syntax:
R=Radiobutton(master,options=value)
Example:
from tkinter import *
import tkinter
def change():
print("station:",var.get())
root=Tk()
root.geometry("300x400")
stations='MCA','MBA','BTECH','MTECH','BSC'
f=Frame(relief=RAISED,borderwidth=9)
var=StringVar()
for station in stations:
radio=Radiobutton(f,text=station,variable=var,value=station).pack(side=TOP)
f.pack(pady=15)
Button(root,text='New',command=(lambda:change())).pack(pady=15)
var.set('WAAL')#initialize the set of radio buttons
mainloop()

7.Slider widget:
It is a tkinter object with which a user can set a value by moving an indicator. Sliders can be
vertically or horizontally arranged. A slider is created with the Scale.
Example:
from tkinter import *
master=Tk()
master.geometry(“300x400”)
w=Scale(master,from_=0,to=50)
w.pack()
w=Scale(master,from_=0,to=200,orient=HORIZONTAL)
w.pack()
mainloop()

8.Listbox widget:
ALLA SUSHMA(MCA)
PYTHON TRAINER
It is used to display a list of alternatives. The list box can only contain text items, and all items
must have the same font and color. Depending on the widget configuration, the user can
choose one or more alternatives from the list.
Example:
from tkinter import *
master=Tk()
master.geometry("500x600")
list=Listbox(master)
list.pack()
list.insert(END,"a list entry")
for item in ["apple","mango","grapes","guva"]:
list.insert(END,item)
mainloop()

9.Scrollbar:
This widget is used to implement scrolled listboxes, canvases and textfields.
Patterns: It is almost always used in conjunction with a listbox, canvas or text widget.
Horizontal scrollbars can also be used in the entry widget.
🡪to connect a vertical scroll bar to such a widget , you have to do two things:
● Set the widget yscrollcommand callbacks to the set method of the scrollbar.
● Set the scrollbar’s command to the yview method of the widget.
Example:
from tkinter import *
master=Tk()
master.geometry("500x500")
scrollbar=Scrollbar(master)
scrollbar.pack(side=RIGHT,fill=Y)
listbox=Listbox(master,yscrollcommand=scrollbar.set)
for i in range(1000):
listbox.insert(END,str(i))
listbox.pack(side=LEFT,fill=BOTH)
scrollbar.config(command=listbox.yview)
mainloop()

10.Canvas:
It is a rectangular area intended for drawing pictures or other complex layouts. You can place
graphics ,text, widgets or frames on a canvas.
Syntax:
ALLA SUSHMA(MCA)
PYTHON TRAINER
W=Canvas(master,option=value…………………)
Example:
Arc: creates an arc item
● coord=10,50,240,210
● arc=Canvas.create_arc(coord,start=0,extent=150,fill=”blue”)
Example:
import tkinter
top=tkinter.Tk()
top.geometry("400x500")
c=tkinter.Canvas(top,bg="blue",height=250,width=300)
coord=10,50,240,210
arc=c.create_arc(coord,start=0,extent=150,fill="yellow")
c.pack()
top.mainloop()

oval: creates a circle or an eclipse at the given coordinates


Syntax:
Ovel=Canvas.create_oval(x0,y0,x1,y1,options)

Example:
from tkinter import *
canvas_width=500
canvas_height=150
def paint(event):
python_red="red"
x1,y1=(event.x-1),(event.y-1)
x2,y2=(event.x+1),(event.y+1)
w.create_oval(x1,y1,x2,y2,fill=python_red)
master=Tk()
master.geometry("400x500")
master.title("painting using ovals")
w=Canvas(master,width=canvas_width,height=canvas_height)
w.pack(expand=YES,fill=BOTH)
w.bind("<B1-Motion>",paint)
message=Label(master,text="press and drag the mouse to draw")
mesage.pack(side=BOTTOM)
mainloop()

BITMAPS:
ALLA SUSHMA(MCA)
PYTHON TRAINER
The method create_bitmap() can be used to include a bitmap on a canvas. The following
bitmaps are available on all platforms:
“error”,”gray75”,”gray50”,”gray25”,”gray12”,”hourglass”,”info”,”questhead”,”question”,”warning
”.
Example:
from tkinter import *
canvas_width=500
canvas_height=90
master=Tk()
canvas=Canvas(master,width=canvas_width,height=canvas_height)
canvas.pack()
bitmaps=["error","gray75","gray50","gray25","gray12","hourglass","info",
"questhead","question","warning"]
nsteps=len(bitmaps)
step_x=int(canvas_width/nsteps)
for i in range(0,nsteps):
canvas.create_bitmap((i+1)*step_x-step_x/2,50,bitmap=bitmaps[i])
mainloop()

11.Menu widget:
It is used to implement toplevel, pulldown and popup menus.

When to use menu widget?


It is used to display all kinds of menus used by an application. Since this widget uses native
code where possible, you shouldn’t try to fake menus using button and other tkinter widgets.

Program:
from tkinter import *
from tkinter import messagebox

ws =Tk()
ws.title("Python Guides")
ws.geometry("300x250")

def about():
messagebox.showinfo('Python', 'Python programming')

menubar = Menu(ws, background='#ff8000', foreground='black',


activebackground='white', activeforeground='black')
ALLA SUSHMA(MCA)
PYTHON TRAINER
file = Menu(menubar, tearoff=1, background='#ffcc99', foreground='black')
file.add_command(label="New")
file.add_command(label="Open")
file.add_command(label="Save")
file.add_command(label="Save as")
file.add_separator()
file.add_command(label="Exit", command=ws.quit)
menubar.add_cascade(label="File", menu=file)

edit = Menu(menubar, tearoff=0)


edit.add_command(label="Undo")
edit.add_separator()
edit.add_command(label="Cut")
edit.add_command(label="Copy")
edit.add_command(label="Paste")
menubar.add_cascade(label="Edit", menu=edit)

help = Menu(menubar, tearoff=0)


help.add_command(label="About", command=about)
menubar.add_cascade(label="Help", menu=help)

ws.config(menu=menubar)
ws.mainloop()

12.spinbox widget:
It is used to select a value from the specific given range of values.
Syntax:
S=Spinbox(master,option=value)
Example:
from tkinter import *
win=Tk()
win.geometry("500x500")
l=Label(win,text="spinbox example",fg="navyblue",font="80")
l.pack()
sb=Spinbox(win,from_=0,to=50)
sb.pack()
win.mainloop()

13.MessageBox widget:
ALLA SUSHMA(MCA)
PYTHON TRAINER
● it provide an appropriate type of message according to the requirement.
● By using this module, we can create pop-up message boxes to take user input.
● It contains functions like showError(), askretrycancel(), showwarning() etc………….
Syntax:
messagebox.function_name(title,message[,options])

Example-1:
from tkinter import *
from tkinter import messagebox
win=Tk()
win.geometry("500x500")
messagebox.showwarning("warning","this is a warning mesg")
win.mainloop()

Example-2:
from tkinter import *
from tkinter import messagebox
win=Tk()
win.geometry("500x500")
messagebox.askquestion("confirm","are you sure quit it?")
win.mainloop()

Example-3:
from tkinter import *
from tkinter import messagebox
win=Tk()
win.geometry("500x500")
messagebox.askretrycancel("application","wanna try again?")
win.mainloop()

Example-4:
from tkinter import *
from tkinter import messagebox
win=Tk()
win.geometry("500x500")
messagebox.showerror("enterwindow","oops!!!error")
win.mainloop()

14.combobox:
ALLA SUSHMA(MCA)
PYTHON TRAINER
A combobox is like a combination of an Entry widget and a Listbox widget.
A combobox allows you to select one value in a list of values.
Example:
import tkinter as tk
from tkinter import ttk

app = tk.Tk()
app.geometry('200x100')

labelTop = tk.Label(app,
text = "Choose month")
labelTop.grid(column=0, row=0)

comboExample = ttk.Combobox(app,
values=[
"January",
"February",
"March",
"April"])
print(dict(comboExample))
comboExample.grid(column=0, row=1)
comboExample.current(1)
print(comboExample.current(), comboExample.get())
app.mainloop()

Tkinter geometry managers:


There are 3 types of geometry managers:
1.pack():
● It is uses mainly packing algorithm in order to place widgets in a frame or window in
specified order.
● This method is mainly used to organize the widgets in a block.
Syntax:
Widget.pack(options)
Options in pack():
● fill: the default value of this option is set to None. Also we can set it ‘X’ or ‘Y’ in order
to determine whether the widget contains any extra space.
● side: if you want to pack widgets vertically, use Top which is the default value. If you
want to pack widgets horizontally, use LEFT.
ALLA SUSHMA(MCA)
PYTHON TRAINER
● expand: it is used to specify whether the widgets should expand to fill any extra space
in the geometry master or not. Its default value is “false”

Example:
import tkinter as tk
win=tk.Tk()
win.geometry("300x300")
frame1=tk.Frame(master=win,height=80,bg="red")
frame1.pack(fill=tk.X)
frame2=tk.Frame(master=win,height=50,bg="yellow")
frame2.pack(fill=tk.X)
frame3=tk.Frame(master=win,height=40,bg="blue")
frame3.pack(fill=tk.X)
win.mainloop()

Example-2:
import tkinter as tk
win=tk.Tk()
win.geometry("300x300")
frame1=tk.Frame(master=win,width=200,height=100,bg="yellow")
frame1.pack(fill=tk.BOTH,side=tk.LEFT,expand=True)
frame2=tk.Frame(master=win,width=100,bg="blue")
frame2.pack(fill=tk.BOTH,side=tk.LEFT,expand=True)
win.mainloop()

2.grid():
It is mainly used to split either a window or frame into rows and columns.
Syntax:
widget.grid(options)
options in grid widget are:
● column: it specifies the column number in which the widget is to be placed.
● row: it specifies the row number in which the widget is to be placed.
● columnspan: it specifies the width of the widget. It mainly represents the no of
columns upto which, the column is expanded.
● rowspan: it specifies the height of the widget , it mainly represents the no of rows
upto which, the rows is expanded.
● padx,pady: it represents the no of pixels of padding to be added to the widget just
outside the widget border.

ALLA SUSHMA(MCA)
PYTHON TRAINER
● ipadx,ipady: it represents the no of pixels of padding to be added to the widget inside
the widget border.
● sticky:it is mainly used to specify the position of the widget inside the cell. It may be
N,E,W,S,NE,NS,NW,EW,ES
Example:
import tkinter as tk
win=tk.Tk()
for i in range(5):
for j in range(3):
frame=tk.Frame(master=win,relief=tk.RAISED, borderwidth=5)
frame.grid(row=i,column=j,padx=5,pady=5)
label=tk.Label(master=frame,text=f"row {i} \n column {j}")
label.pack()
win.mainloop()

3.place():
● it organize the widgets to place them in a specific position as directed by the
programmer.
● Thus the origin( where x and y are both 0) is the top-left corner of the Frame or the
window.
● Thus, the ‘y’ argument specifies the no.of pixels of space from the top of the window,
to place the widget, and the ‘x’ argument specifies the no of pixels from the left of the
window.
Syntax:
widget.place(option)

options of the place() layout manager:


● x,y:indicates horizontal and vertical offset in the pixels.
● height,width: indicates height and width of the widget in the pixels.
● anchor: it represents the exact position of the widget within the container. The default
value is NW(upper left corner).
● relx,rely: represent the float between 0.0 and 1.0 and it is offset in the horizontal and
vertical direction.
● relheight ,relwidth: represents the float value between 0.0 and 1.0 indicating the
fraction of the parents height and width.
Example:
from tkinter import *
top=Tk()
top.geometry("500x500")
ALLA SUSHMA(MCA)
PYTHON TRAINER
username=Label(top,text="username").place(x=30,y=50)
email=Label(top,text="Email").place(x=30,y=90)
password=Label(top,text="password").place(x=30,y=130)
e1=Entry(top).place(x=80,y=50)
e2=Entry(top).place(x=80,y=90)
e3=Entry(top).place(x=95,y=130)
top.mainloop()

Application-1:
Calculator Example in python:
# import everything from tkinter module
from tkinter import *
  
# globally declare the expression variable
expression = ""
  
  
# Function to update expressiom
# in the text entry box
def press(num):
    # point out the global expression variable
    global expression
  
    # concatenation of string
    expression = expression + str(num)
  
    # update the expression by using set method
    equation.set(expression)
  
  
# Function to evaluate the final expression
def equalpress():
    # Try and except statement is used
    # for handling the errors like zero
    # division error etc.
  
    # Put that code inside the try block
    # which may generate the error
    try:
  
        global expression
  
        # eval function evaluate the expression
ALLA SUSHMA(MCA)
PYTHON TRAINER
        # and str function convert the result
        # into string
        total = str(eval(expression))
  
        equation.set(total)
  
        # initialze the expression variable
        # by empty string
        expression = ""
  
    # if error is generate then handle
    # by the except block
    except:
  
        equation.set(" error ")
        expression = ""
  
  
# Function to clear the contents
# of text entry box
def clear():
    global expression
    expression = ""
    equation.set("")
  
  
# Driver code
if __name__ == "__main__":
    # create a GUI window
    gui = Tk()
  
    # set the background colour of GUI window
    gui.configure(background="light green")
  
    # set the title of GUI window
    gui.title("Simple Calculator")
  
    # set the configuration of GUI window
    gui.geometry("265x125")
  
    # StringVar() is the variable class
    # we create an instance of this class
    equation = StringVar()
  
    # create the text entry box for
ALLA SUSHMA(MCA)
PYTHON TRAINER
    # showing the expression .
    expression_field = Entry(gui, textvariable=equation)
  
    # grid method is used for placing
    # the widgets at respective positions
    # in table like structure .
    expression_field.grid(columnspan=4, ipadx=70)
  
    equation.set('enter your expression')
  
    # create a Buttons and place at a particular
    # location inside the root window .
    # when user press the button, the command or
    # function affiliated to that button is executed .
    button1 = Button(gui, text=' 1 ', fg='black', bg='red',
                     command=lambda: press(1), height=1, width=7)
    button1.grid(row=2, column=0)
  
    button2 = Button(gui, text=' 2 ', fg='black', bg='red',
                     command=lambda: press(2), height=1, width=7)
    button2.grid(row=2, column=1)
  
    button3 = Button(gui, text=' 3 ', fg='black', bg='red',
                     command=lambda: press(3), height=1, width=7)
    button3.grid(row=2, column=2)
  
    button4 = Button(gui, text=' 4 ', fg='black', bg='red',
                     command=lambda: press(4), height=1, width=7)
    button4.grid(row=3, column=0)
  
    button5 = Button(gui, text=' 5 ', fg='black', bg='red',
                     command=lambda: press(5), height=1, width=7)
    button5.grid(row=3, column=1)
  
    button6 = Button(gui, text=' 6 ', fg='black', bg='red',
                     command=lambda: press(6), height=1, width=7)
    button6.grid(row=3, column=2)
  
    button7 = Button(gui, text=' 7 ', fg='black', bg='red',
                     command=lambda: press(7), height=1, width=7)
    button7.grid(row=4, column=0)
  
    button8 = Button(gui, text=' 8 ', fg='black', bg='red',
                     command=lambda: press(8), height=1, width=7)
    button8.grid(row=4, column=1)
ALLA SUSHMA(MCA)
PYTHON TRAINER
  
    button9 = Button(gui, text=' 9 ', fg='black', bg='red',
                     command=lambda: press(9), height=1, width=7)
    button9.grid(row=4, column=2)
  
    button0 = Button(gui, text=' 0 ', fg='black', bg='red',
                     command=lambda: press(0), height=1, width=7)
    button0.grid(row=5, column=0)
  
    plus = Button(gui, text=' + ', fg='black', bg='red',
                  command=lambda: press("+"), height=1, width=7)
    plus.grid(row=2, column=3)
  
    minus = Button(gui, text=' - ', fg='black', bg='red',
                   command=lambda: press("-"), height=1, width=7)
    minus.grid(row=3, column=3)
  
    multiply = Button(gui, text=' * ', fg='black', bg='red',
                      command=lambda: press("*"), height=1, width=7)
    multiply.grid(row=4, column=3)
  
    divide = Button(gui, text=' / ', fg='black', bg='red',
                    command=lambda: press("/"), height=1, width=7)
    divide.grid(row=5, column=3)
  
    equal = Button(gui, text=' = ', fg='black', bg='red',
                   command=equalpress, height=1, width=7)
    equal.grid(row=5, column=2)
  
    clear = Button(gui, text='Clear', fg='black', bg='red',
                   command=clear, height=1, width=7)
    clear.grid(row=5, column='1')
  
    # start the GUI
    gui.mainloop()

Application-2:
By using all GUI components(application form):
from tkinter import *
from tkinter.ttk import Combobox
from tkcalendar import *
from tkinter import filedialog
window=Tk()
window.geometry("700x700")
window.title("Application Form")
ALLA SUSHMA(MCA)
PYTHON TRAINER
#creating Name window
Name=StringVar()
l1=Label(window,text="Name : ",font="verdana 14")
e1=Entry(window,font="verdana 14")
l1.grid(row=0,column=0)
e1.grid(row=0,column=2,pady=5)

#creating email window


Email=StringVar()
l2=Label(window,text="Email:",font="verdana 14")
l2.grid(row=1,column=0)

e2=Entry(window,font="verdana 14")
e2.grid(row=1,column=2,pady=10)

b=Button(window,text="@",font="verdana 14")
b.grid(row=1,column=3)

c_mail=Combobox(window,values=["google.com","yahoo.com","reddit.com","outlook.com"]
,font="verdana 14")
c_mail.grid(row=1,column=4)

#creating mobile number


Mobile_Number=StringVar()

l3=Label(window,text="Mobile number:",font="verdana 14")


e3=Entry(window,font="verdana 14")
l3.grid(row=2,column=0)
e3.grid(row=2,column=2,pady=10)

#creating qualification
Qualificaiton=StringVar()
qual=Label(window,text="Qualificaiton :",font="verdana 14")
qual.grid(row=3,column=0,pady=10)

qual_branch=Combobox(window,values=["b.tech","m.tech","mca","msc"],font="verdana
14")
qual_branch.grid(row=3,column=2,pady=10)

#creating Percentage
Percentage=StringVar()
per=Label(window,text="Percentage :",font="verdana 16")
per.grid(row=5,column=0,pady=10)

ALLA SUSHMA(MCA)
PYTHON TRAINER
cper=Combobox(window,values=["90-100 %","80-90 %","70-80 %","60-70 %"],font="verdana
14")
cper.grid(row=5,column=2,pady=10)

def clicked_dob():
def grab_date():
e_dob.config(text=mycal.get_date())
mycal=Calendar(window,selectmode="day",year=2020,month=1,day=1)
mycal.grid(row=7,column=3,pady=10)
grab_date()

"""cal=StringVar()
options=["day","month","year"]"""

# year of birth
Year_Of_Pass=StringVar()
yop=Label(window,text="year of pass : ",font="verdana 16")
yop.grid(row=6,column=0,pady=10)

l=[]
for i in range(2014,2021):
l.append(i)
e_yop=Combobox(window,values=l,font="verdana 14")
e_yop.grid(row=6,column=2,pady=10)

#Date of Birth
Date_Of_Birth=StringVar()
dob=Label(window,text=" date of birth: ",font="verdana 16")
dob.grid(row=7,column=0,pady=15)

e_dob=DateEntry(window,font="verdana 14",width=20)
e_dob.grid(row=7,column=2,pady=15)

#gender
v=StringVar()
v.set(' ')
gen=Label(window,text="Gender :",font="verdana 14")
gen.grid(row=8,column=0,pady=10)

def val():
global info
info=v.get()

ALLA SUSHMA(MCA)
PYTHON TRAINER
r1=Radiobutton(window,text="Male",value="male",variable=v,font="verdana
14",command=val)
r1.deselect()
r1.grid(row=8,column=2,pady=10)

r2=Radiobutton(window,text="Female",value="female",variable=v,font="verdana
14",command=val)
r2.deselect()
r2.grid(row=8,column=3,pady=10)

r3=Radiobutton(window,text="others",value="others",variable=v,font="verdana
14",command=val)
r3.deselect()
r3.grid(row=8,column=4,pady=10)

#creating check boxes


S=StringVar()
skills=Label(window,text="Skills :",font="verdana 14")
skills.grid(row=9,column=0,pady=10)

var1=StringVar()
var2=StringVar()
var3=StringVar()

e1_skill=Checkbutton(window,text="python",font="verdana
14",variable=var1,onvalue="python",offvalue=" ")
e1_skill.deselect()
e1_skill.grid(row=9,column=2)

e2_skill=Checkbutton(window,text="java",font="verdana
14",variable=var2,onvalue="java",offvalue=" ")
e2_skill.deselect()
e2_skill.grid(row=9,column=3)

e3_skill=Checkbutton(window,text="data science",font="verdana
14",variable=var3,onvalue="data science",offvalue=" ")
e3_skill.deselect()
e3_skill.grid(row=9,column=4)

#creating text box

ALLA SUSHMA(MCA)
PYTHON TRAINER
text=Label(window,text="Somethig about you:",font="verdana 12")
text.grid(row=10,column=0)

e_text=Text(window,width=25,height=4,font="verdana 12")
e_text.grid(row=10,column=2,pady=15)

# creating submitting button


def application():
root=Tk()
root.geometry("500x500")
root.title("the details of applicant")
name_of_user="Name : "+e1.get()
l1=Label(root,font="verdana 12")
l1["text"]=name_of_user
l1.grid(row=0,column=0,sticky="nw",pady=10)

#getting email from the user


email_of_the_user="Email : "+e2.get()+"@"+c_mail.get()
l2=Label(root,font="verdana 12")
l2["text"]=email_of_the_user
l2.grid(row=1,column=0,sticky="nw",pady=10)

#getting phone number from the user


phone_user="Mobile Number : "+e3.get()
l3=Label(root,font="verdana 12")
l3["text"]=phone_user
l3.grid(row=2,column=0,sticky="nw",pady=10)

#getting qualification from the user


qual_user="qualification : "+qual_branch.get()
l4=Label(root,font="verdana 12")
l4["text"]=qual_user
l4.grid(row=3,column=0,sticky="nw",pady=10)

#getting percentage from the user


per_user="percentage : "+ cper.get()
l5=Label(root,font="verdana 12")
l5["text"]=per_user
l5.grid(row=4,column=0,sticky="nw",pady=10)

#getting year of pass from the user


e_user="year of pass : "+e_yop.get()
l6=Label(root,font="verdana 12")
l6["text"]=e_user
l6.grid(row=5,column=0,sticky="nw",pady=10)
ALLA SUSHMA(MCA)
PYTHON TRAINER
#getting date of birth from the user
e_dob_user="date of birth : "+e_dob.get()
l7=Label(root,font="verdana 12")
l7["text"]=e_dob_user
l7.grid(row=6,column=0,sticky="nw",pady=10)

#getting gender from the user


gen_user="Gender :"+v.get()
l8=Label(root,font="verdana 12")
l8["text"]=gen_user
l8.grid(row=7,column=0,sticky="nw",pady=10)

#getting skills from the e_user


e1_skill_user="Skills :"+var1.get()
e2_skill_user=" "+var2.get()
e3_skill_user=" "+var3.get()
l9=Label(root,font="verdana 12")
l9["text"]=e1_skill_user
l9.grid(row=8,column=0,sticky="nw",pady=10)

l10=Label(root,font="verdana 12")
l10["text"]=e2_skill_user
l10.grid(row=9,column=0,sticky="nw",pady=5,padx=50)

l11=Label(root,font="verdana 12")
l11["text"]=e3_skill_user
l11.grid(row=10,column=0,sticky="nw",pady=5,padx=50)

#getting feedback
e_user="Somethig about yourself :"+e_text.get(1.0,END)
l10=Label(root,font="verdana 12")
l10["text"]=e_user
l10.grid(row=11,column=0,sticky="nw",pady=10)

#creating save file button


def save_data():
file=filedialog.asksaveasfile(defaultextension=".txt",
filetypes=[
("Text file",".txt"),
("pdf file",".pdf"),
("html file",".html")
])
list=[name_of_user ,"\n ",email_of_the_user , "\n",phone_user, "\n",qual_user," \n",
e_dob_user ,"\n",
ALLA SUSHMA(MCA)
PYTHON TRAINER
gen_user," \n",e1_skill_user ,"\n",e2_skill_user ,"\n",e3_skill_user," \n",e_user," "]
file.writelines(list)

quit=Button(root,text="Exit",command=root.destroy,font="verdana 12")
quit.grid(row=12,column=2,pady=40,sticky="nw")

save=Button(root,text="save this data",font="verdana 12",command=save_data)


save.grid(row=12,column=0,sticky="nw",pady=40)

root.mainloop()

s=Button(window,text="Submit",command=application,font="verdana 14")
s.grid(row=12,column=2,pady=25)

#creating clear button


def clear_app():
#e1.delete(0,END)
Name.set(' ')
e2.delete(0,END)
c_mail.delete(0,END)
e3.delete(0,END)
qual_branch.delete(0,END)
cper.delete(0,END)
e_dob.delete(0,END)
e_yop.delete(0,END)
v.set(' ')

var1.set(' ')
var2.set(' ')
var3.set(' ')
e_text.delete(1.0,END)

s=Button(window,text="Clear",command=clear_app,font="verdana 14")
s.grid(row=12,column=0,pady=25)

quit=Button(window,text="Exit",command=window.destroy,font="verdana 14")
quit.grid(row=12,column=3,pady=25)
window.mainloop()
ALLA SUSHMA(MCA)
PYTHON TRAINER
Application-3: (QR code generator)
import pyqrcode
from pyqrcode import QRCode
s="qr code generator program"
gqr=pyqrcode.create(s)
gqr.svg("qrcode.svg",scale=8)
gqr.png("qrcode.png",scale=6)

FILES INPUT/OUTPUT
File handling:
A file is an external storage on hard disk from where data can be stored and retrieved.

Operations on files:
1.opening a file: to open a file use open() function. It returns an object of file which is used
with other functions.
Syntax:
Obj=open(filename,mode,buffer)

2.closing a file: once you are finished with the operation on file at the end you need to close
the file. It is done by the close() method.

3.write to a file file.write() is use to write a string into the file.


Syntax:
File object.write(String str)

4.reading from a file: read() method is used to read data from the file.
Syntax:
File object.read(value)

Attributes of file:
● Name: returns the name of the file
● Mode: returns the mode in which file is being opened
● Closed: returns Boolean value. True, in case if file is closed else false.
Example:
obj=open("python.txt","w")
print(obj.name)
print(obj.mode)
print(obj.closed)
ALLA SUSHMA(MCA)
PYTHON TRAINER
modes of file:
Mode Description
r It opens in reading mode. It is default mode of a file. Pointer is at beginning of
the file.
rb It opens in reading mode for binary format. It is default mode. Pointer is at
beginning of the file
r+ Opens file for reading and writing
rb+ Opens file for reading and writing in binary format
w Opens a file in writing mode. If file already exists then overwrite the file else
create a new file
wb Opens a file in writing mode in binary format
w+ Opens a file for reading and writing
wb+ Opens a file for reading and writing in binary format
a File in appending mode
ab Appending mode in binary format
a+ Opens file in reading and appending mode
ab+ Opens a file in reading and appending mode in binary format.

Example:
obj=open("sush.txt","w")
obj.write("today we are discussing files concepts")
obj.close()
obj1=open("sush.txt","r")
s=obj1.read()
print(s)
obj1.close()
obj2=open("sush.txt","r")
s1=obj2.read(20)
print(s1)
obj2.close()

Example:
#copying a data from one file to another file
file1=open("sush.txt","r")
file2=open("mani.txt","w")
Reader=file1.read()
file2.write(Reader)
file1.close()
file2.close()

ALLA SUSHMA(MCA)
PYTHON TRAINER
MYSQL
● It is a database system, used for developing web-based software applications.
● It is used for both small and large applications.
● It is RDBMS(relational database management system)
● It is fast reliable and flexible and easy to use.
● It supports standard sql
● It was developed by ‘michael widenius’ and ‘David Axmarx’ in 1994.
● It is presently developed, distributed and supported by oracle corporation.
● It is written in c,c++

Features of mysql:
● MYSQL server design is multi-layered with independent modules.
● It is fully multithreaded by using kernel threads. It can use multiple CPU’s if they
are available
● It provides transactional and non-transactional storage engines.
● It has high speed thread based memory allocation system.
● It supports memory heap table
● It handles large databases
● MYSQL server works in client and server or embedded systems.
● It work on different platform.

Who uses mysql?


● Some of the most famous websites like Facebook, Wikipedia, Google, Youtube, Flickr.
● Content managements systems(CMS) like WordPress, Drupal, Joomla, PhpDB.

Types of SQL commands:


1.DDL(data definition language):
It deals with database schemas and descriptions , of how the data should reside in the
database.
(a)CREATE:
To create a database and its objects like(tables, indexes, views, store procedures, functions
and triggers).
(b)ALTER: alter the structure of the existing database
(c)DROP: delete the objects from the database.
(d) TRUNCATE: remove all records from a table , including all spaces allocated for the records
are removed
ALLA SUSHMA(MCA)
PYTHON TRAINER
(e) RENAME: rename the objects

2.DML(data manipulation languages):


It is used to store , modify, retrieve, delete and update the data in a database.
(a)SELECT: retrieve data from the database.
(b)INSERT: insert the data within a table.
(c)UPDATE: updates the existing data within a table.
(d)DELETE: delete all records from a database table.
(e)MERGE: insert or update
(f)CALL: call pl/sql or java subprogram
(g)EXPLAIN PLAIN: interpretation of the data access path.
(h)LOCK TABLE: concurrency control

3.DCL(data control language):


(a)GRANT: allows the user access privileges to the database.
(b)REVOKE: withdraw user access privileges given by using the GRANT command.

4.TCL(transactional control language):


(a)COMMIT: commits a transaction
(b)ROLLBACK: rollback the transaction making points within groups.
(c)SAVEPOINT: to rollback the transaction making points within groups.
(d)SET TRANSACTION:specify characteristics of the transaction.

Create database and use database:


Database syntax:
Create database database_name;
Syntax to use database:
Use database_name;

Example:
mysql>create database college;
mysql>show databases;
mysql>use college;
database changed

Create a table:
Syntax:
create table table_name(col1 datatype,col2 datatype….);
Example:
create table student(rollno int,name varchar(10),address varchar(5),branch varchar(5));
Table created
ALLA SUSHMA(MCA)
PYTHON TRAINER
Describing a table:
Syntax:
desc table_name;
Example:
desc student;

Modifying the structure of the table:


Alter table command:
It is used to add new columns to a table,remove existing columns and changing column
names,types and lengths.
To add new fields in table:
Syntax:
ALTER TABLE table_name add[column] column definition [first/after column];
Example:
alter table student add result int;
desc student;

Example:1
alter table student add id int first;
desc student;

Example:2
alter table student add address varchar(10) after name;
desc student;

Drop a column:
The drop clause of the ALTER TABLE statement removes a given column from a table and
deletes the columns data.A table must have at least one column,so this statement will fail if
used on the only column in a table.
Syntax:
ALTER TABLE table_name DROP[COLUMN] column_name;
Example:
alter table student drop column id;
desc student;
Example:2
alter table student drop column branch,drop column result;
desc student;

MODIFY,CHANGE,RENAME:
1.modify:
This clause used to change the data types of an existing column.
Syntax:
alter table tablename modify column_name data_type;
Example:
ALLA SUSHMA(MCA)
PYTHON TRAINER
alter table student modify address varchar(12);
desc student;

2.change:
This clause used to change the name of an existing column.
Syntax:
ALTER TABLE table_name change column_name new_column_name data_type;
Example:
alter table student change address location varchar(12);
desc student;

3.rename:
This clause used to rename the table name.
Syntax:
ALTER TABLE table_name rename new_name;
Example:
alter table student rename comp;
desc student;
Error 1146(42s02):Table ‘college.student’ doesn’t exist
desc comp;

Insert data into tables:


This command used to insert data into the table.
Syntax:
INSERT into <table-name>values (val1,val2 etc…..);
Example:
insert into student values(11,’mani’,’hyd’);
select * from student;

Example:2
insert into student values(12,’sushma’,’hyd’),(13,’anil’,’hyd’);
select * from student;

Delete the data from table:


Syntax:
DELETE from <table-name> where (<column-name>=’some-value’);
Example:
delete from student where rollno=10;
select * from student;

Example:2
delete from student;
select * from student;

ALLA SUSHMA(MCA)
PYTHON TRAINER
Limit keyword with delete:
Using the LIMIT keyword to ensure only the number of rows you specify are deleted.
Example:
delete from student limit 2;
select * from student;

update data into tables:


Syntax:
UPDATE tablename set column_name=value where condition;
Example:
update student set name=’padma’ where id=12;
select * from student;

Example:1
update student set name=’mani’;
select * from student;

Example:3
update student set id=id+1;
select * from student;

NOTE:
Use the LIMIT function to display to control the no.of rows that are affected by your UPDATE
statement.
Example:
update student set name=’manikumar’ limit 2;
select * from student;

DATABASE PROGRAMMING IN PYTHON


🡪Python supports various databases like MYSQL,ORACLE,SYBASE,POSTGRESQL, etc…
🡪Python also supports DDL,DML and Data query statements.
🡪Python DB API is a widely used module that provides a database application programming
interface.

Benefits of python for database programming:


1.Python is famous for its portability.
2.It is platform independent.
3.Python supports SQL cursors.
4.Python supports relational database management system.
5.Python database API’s are compatable with various databases, so it is very easy to migrate
and port databases application interface.

ALLA SUSHMA(MCA)
PYTHON TRAINER
Steps to connect MYSQL database in python using MYSQL connector python:
1.Install MYSQL connector python using pip.
Example:
C:\users\your name\App data\Local\Programs\Python\Python 36-32\Scripts>python –m pip
install mysql-connector.
2.use the mysql.connector.connect() method of MYSQL connector python with required
parameters to connect MYSQL.
3.use the connection object returned by a connect() method to create a cursor object to
perform database operations.
4.The cursor.execute() to execute SQL queries from python.
5.close the cursor object using a cursor.close() and MYSQL database connection using
connection.close() after your work completes.
6.Catch exception if any that may occur during this process.

Packages:
1.import mysql.connector:
This module API to connect MYSQL.
2.from mysql.connector import error:
It show us an error when we failed to connect database (or) if any other databases object
error occurred while working with the database.
Example:
ER_Access_DENIED_Error when username (or) password is wrong.

Arguments required to connect the MYSQL database from python:


(a)username:
The default username for the MYSQL database is ‘root’.
(b)password:
Password is given by the user at the time of installing the MYSQL database. If you are using
root then you won’t need the password.
(c) hostname:
It is server name (or) IP address on which MYSQL is running. If you are running on localhost,
then you can use localhost, (or) it’s IP,i.e 127.0.0.0
(D)database name:
Database name to which you want to connect here we are using database named
‘Python_DB’.

Functions:
(1)mysql.connector.connect:
🡪This function we can connect the MYSQL database, this function accepts four required
parameters:Host,Database,user and password that we already discussed.
🡪connect() function established a connection to the MYSQL database from python
application and returnd a MYSQLConnection object.
🡪connect() function throw an exception,i.e. database error if one of the required parameters
are wrong.

ALLA SUSHMA(MCA)
PYTHON TRAINER
(2)conn.is_connected():
It is the function of the MySQLConnection class through which we can verify is our python
application connected to MySQL.

(3)connection.cursor():
It returns a cursor object, using this object we can execute SQL queries. Cursor objects
interact with the MySQL server using a MySQLConnection object.

(4)cursor.close():
Using this method we can close the cursor object.Once we close the cursor object, we can not
execute any SQL statement.

(5)connection.close():
Closing the MySQL databases connection using a close() function of MySQLConnection class.

Program-1:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="manikumar"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE hospital")


print("Database Created Success..!")

Program-2:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="manikumar",
database="hospital"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE patients(name varchar(10),address varchar(10))")

print("Table Created Success")

ALLA SUSHMA(MCA)
PYTHON TRAINER
Program-3:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="manikumar",
database="hospital"
)

mycursor = mydb.cursor()
sql = "INSERT INTO patients(name,address) VALUES (%s,%s)"
val = ('sushma','vizag')

mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")

Program-4:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="manikumar",
database="hospital"
)

print("Enter Customer Name : ")


name=input()
print("Enter Customer Address : ")
address=input()

mycursor = mydb.cursor()
sql = "INSERT INTO patients(name, address) VALUES (%s, %s)"
val = (name, address)
mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")

ALLA SUSHMA(MCA)
PYTHON TRAINER
Program-5:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="manikumar",
database="hospital"
)

mycursor = mydb.cursor()

sql = "INSERT INTO patients(name, address) VALUES (%s, %s)"


val = [
('Peter', 'usa'),
('Amy', 'mumbai'),
('Hannah', 'chennai'),
('Michael', 'punjab'),
('Sandy', 'assam'),
('Betty', 'goa'),
('Richard', 'haryana'),
('Susan', 'gujarat'),
('Vicky', 'delhi'),
('Ben', 'kolkatha'),
('William', 'banglore'),
('Chuck', 'ooty'),
('Viola', 'mysore')
]

mycursor.executemany(sql, val)

mydb.commit()
print("Records Inserted")

Program-6:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="manikumar",
database="hospital"
)

mycursor = mydb.cursor()
ALLA SUSHMA(MCA)
PYTHON TRAINER
mycursor.execute("SELECT * FROM patients")

myresult = mycursor.fetchall()

for x in myresult:
print(x)

Program-7:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="manikumar",
database="hospital"
)

print("Enter name: ")


name=input()
print("Enter address: ")
address=input()

mycursor = mydb.cursor()
sql = "UPDATE patients set address=%s where name=%s"
val = (address,name)
mycursor.execute(sql, val)

mydb.commit()

if(mycursor.rowcount==1):
print(mycursor.rowcount, "record updated Success.")
else:
print(mycursor.rowcount, "record updated Failed.")

Program-8:
from tkinter import *
import mysql.connector
from tkinter import ttk
from tkinter import messagebox

window = Tk()

window.title("Faculity Form")

ALLA SUSHMA(MCA)
PYTHON TRAINER
window.geometry('550x300')

id=""
name=""
experience=0
salary=""
gen=""

lbl = Label(window, text="Enter Faculity ID : ",font=("Arial",25))

lbl.grid(column=0, row=0)

txtid = Entry(window,width=10)
txtid.focus()
txtid.grid(column=1, row=0)

lbl1 = Label(window, text="Enter Faculity Name : ",font=("Arial",25))

lbl1.grid(column=0, row=1)

txtname = Entry(window,width=10)
txtname.grid(column=1, row=1)

lbl2 = Label(window, text="Select Faculity Experiance : ",font=("Arial",25))

lbl2.grid(column=0, row=2)

combo =ttk.Combobox(window)

combo['values']= ("1", "2", "3", "4", "5", "6","7", "8", "9", "10","--Select--")

combo.current(10) #set the selected item

def getExp(eventObject):
experience=int(combo.get())

combo.bind("<<ComboboxSelected>>", getExp)
combo.grid(column=1, row=2)

lbl3 = Label(window, text="Enter Faculity Salary : ",font=("Arial",25))


lbl3.grid(column=0, row=3)

txtsal = Entry(window,width=10)
txtsal.grid(column=1, row=3)

ALLA SUSHMA(MCA)
PYTHON TRAINER
selected = IntVar()
rad1 = Radiobutton(window,text='M', value=1, variable=selected)
rad1.grid(column=0, row=4)
rad2 = Radiobutton(window,text='F', value=2, variable=selected)
rad2.grid(column=1, row=4)

def clicked():
id=txtid.get()
name=txtname.get()
salary=txtsal.get()
experience=combo.get()
if(selected.get()==1):
gen="M"
else:
gen="F"
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="manikumar",
database="institute")
mycursor = mydb.cursor()
sql = "INSERT INTO faculty(fid,fname,fexp,sal,gen) VALUES (%s,%s, %s,%s,%s)"
val = (id,name,experience,salary,gen)
mycursor.execute(sql, val)
mydb.commit()
messagebox.showinfo('Faculity Form', 'Successfully Submited')

btn = Button(window, text="Submit", command=clicked)

btn.grid(column=0, row=5)

window.mainloop()

Program-9:
from tkinter import *
from tkinter.filedialog import askopenfilename

window = Tk()

window.title("File Reader")

window.geometry('550x300')

lbl = Label(window, text="Select your file : ",font=("Arial",25),fg="white",bg="red")

ALLA SUSHMA(MCA)
PYTHON TRAINER
lbl.grid(column=0, row=0)

txtpath = Entry(window,width=20,font=("Arial",25),fg="white",bg="pink")
txtpath.grid(column=1, row=0)

def openwind():
name= askopenfilename()
txtpath.insert(0, name)

btnBrowse = Button(window, text="***",


command=openwind,font=("Arial",25),fg="white",bg="red")

btnBrowse.grid(column=2, row=0)

obj=Text(window,height=10,width=50)
obj.grid(column=0,row=1)

def getFile():
f = open(txtpath.get(), "r")
for line in f.readlines():
obj.insert(END,line)
btnOpen = Button(window, text="Open",
command=getFile,font=("Arial",25),fg="white",bg="red")
btnOpen.grid(column=0, row=2)
window.mainloop()

ALLA SUSHMA(MCA)
PYTHON TRAINER

You might also like