0% found this document useful (0 votes)
0 views

1-Core Python Material

Uploaded by

netmirror36
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

1-Core Python Material

Uploaded by

netmirror36
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 109

Python Language Fundamentals:

Introducion
Application areas of python
Features of python
Limitations of python
Flavours of python
Python versions
Indentifiers
Reserved words
Data Types
:14 data types
:Type casting

1.Introduction:
what is python and Father of python
--Python is a general purpose Highlevel Programing Language
--Father Of Phython is GuidoVanRossum in 1991 Fe 20th(First
Public Version is Released)
Easyness of python when compared with Other Languages
--less code(concise code)
--not required to data type(its a dynamically typed)
--c and c++ and java statically typed
Why the name python(the complete monty python's flying circus)
Why Python as all Rounder
--C is a Functional Programing Language

def f1():
print('It is a functional programing
language')
print('It is a functional programing
language')
print('It is a functional programing
language')
print('It is a functional programing
language')
print('It is a functional programing
language')
f1()

--c++, java are Object Oriented Programing Language

class test:
`def f1(self):
print('It is a functional programing
language')
print('It is a functional programing
language')
print('It is a functional programing
language')
print('It is a functional programing
language')
print('It is a functional programing
language')
t=test()
t.f1()

--Perl, Shell Script are Scripted Language


print('It is a functional programing
language')
print('It is a functional programing
language')
print('It is a functional programing
language')
print('It is a functional programing
language')
print('It is a functional programing
language')
--So Python as All Rounder and Most Of The Syntaxes used as
barrowed from C and ABC Languages

2.Where we can use Python


--DeskTop Application(The Applications which are running in a
single System) Eg:caliculator,vlc
--Web Applications(GMAIL,FACEBOOK,BLOG)
--NetWork Applications
--Games Devolopment
--Data Analysis / Data Science
--ML(MACHINE LEARNING),DL(DEEP LEARNING),AI(ARTIFICIAL
INTELLIGENCE),IOT

Top Companies using


Python:GOOGLE,FACEBOOK,INSTAGRAM,QUORA,NETFLIX,DROPBOX,NASA...ETC

3.Features Of Python
1--Simple and Easy to Learn
Total Python Keywords are only 33
Other Application Files are easy to access into the
python
Eg:1 print(open('naresh.txt').read())
Eg:2 a=10 b=10
aisb
Eg:3 if emp is not none:

2--Freeware and Open Source


Python Software was Available from Python.Org site.Its
Maintains PSF.Its free of cost.
Freeware:JAVA - oracle(its a business purpose)
C#.NET - Microsoft(Its a business purpose)
Python - PSF(Python Software Foundation) Its not
a business purpose.
Open Source: Every one customize the Python
If we want to work PYTHON with java Application
(JYTHON SOFTWARE)
If we want to work PYTHON with C#.NET Application
(IRON PYTHON SOFTWARE)
If we want to work PYTHON with BIGDATA Application
(ANAKONDA PYTHON SOFTWARE) ETC ..MULTIPLE FLAVOURS ARE AVAILBLE.

3--High Level Programing Language


Its a programmer friendly Language.No worried
About required for Low level activities like memory allocation,destroy
the data,security etc.,because it maintains totally PVM(Python Virtual
Machine).
4--Platform Independent:write once run any where
Python Application is Independent and pvm(python
virtual machine) is a dependent.
5--Portbility:Migrating the Application from one platform to
another Plat Form very easily.
eg:Portable tv and mobile number portbility same
like application portabl in python
6--Dynamically Typed:
7--Both Procedure and Object Oriented:python is an all rounder
8--Interpreted:compile is not required in python
9--Extensible:other languages Applications are used in python
10--Embedded:in other language Application python scripts are
used
11--Extensive Libruary.....etc
--from random import randint
for i in range(10):

print(randint(0,9),randint(0,9),randint(0,9),randint(0,9),randint(0,9),ra
ndint(0,9),sep=' ')
4.Limitations of python:

--some areas python is not work properly


--ML(MACHINE Learning) -to devolope the machine learning
Application Python is the best choice
numpy(mathematics library),pandas(import dataset
library),matplot library(for import graphchart....)
all these modules are devolope the ML, Python Library
are available.

Python is not suitable for these Application:


1.Mobile Application
2.EnterPrize Application
Eg:Banking Applications
Telecom Applications
3.Performance is low because Python is a interpreted
Application
overtake this problem JIT COMPILER is added to PVM
JITCOMPILER+PVM---PYPY Flavour(PYTHON FOR SPEED)

5.Flavours of python:
--Free ware and Open Source
Free ware -Free of cost from PSF
Open Source -This is mainly used for Customized
Python versions are develope.
So Multiple Python Flavours are developed by
open source.

Multiple Flavours are available through Python-


1.Cpython -Standard Version of Python,to work with
c-language Application
2.Jython or JPython-to work with java Language
Applications
3.Iron Python -to work with c#.net Language
Applications
4. Ruby Python -to work with Ruby Application
5. Anakonda Python - to work with Large Volumes of datas
are DataScience,ML,IOT AND Artificial Inteligency..etc
6.Stackless Python -to work cocurancy Applications
7.Pypy Python -Python for speed(Jit
compiler+pvm) overtake the low performance.

6.Python versions
1.Python 0.9.0 - February 20, 1991
--Python 0.9.1 - February, 1991
--Python 0.9.2 - Aug, 1991
--Python 0.9.4 - December 24, 1991
--Python 0.9.5 - January 2, 1992
--Python 0.9.6 - April 6, 1992
--Python 0.9.8 - January 9, 1993
--Python 0.9.9 - July 29, 1993
2.Python 1.0 - January 1994
--Pyhton 1.2 - April 10, 1995
--Pyhton 1.3 - October 12, 1995
--Pyhton 1.4 - October 25, 1996
--Pyhton 1.5 - December 31, 1997
--Pyhton 1.6 - September 5, 2000
3.Python 2.0 - October 16, 2000(.........It is py2k)
--Pyhton 2.1 - April 15, 2001
--Pyhton 2.2 - December 21, 2001
--Pyhton 2.3 - July 29, 2003
--Pyhton 2.4 - November 30, 2004
--Pyhton 2.5 - September 19, 2006
--Pyhton 2.6 - October 1, 2008
--Pyhton 2.7 - July 3, 2010
4.Python 3.0 - December 3, 2008
--Pyhton 3.1 - June 27, 2009
--Pyhton 3.2 - February 20, 2011
--Pyhton 3.3 - September 29, 2012
--Pyhton 3.4 - March 16, 2014
--Pyhton 3.5 - September 13, 2015
--Pyhton 3.6 - December 23, 2016
--Pyhton 3.7 - June 27, 2018
--latest Python 3.9.5 ...2021
Note:Python 2x and Python 3x version are not support backward
compatibility......
but java11..java 10.. and before versions are support
backward compatibility.
7.Identifiers :
--Names for Variables,names for the methods and names for the
classes are Identifier names.
--Rules For the Identifiers:
1.Identifiers are must formed with Alphabets(atoz and
AtoZ),Numaric(0-9) and Underscorer ( _ ) Character in any order.
2.In the identifier names First Character must not be a digit.
eg:
total123=10 (is valid)
123total=10(is not valid)
3.In Python Identifiers are Case sensitive
eg:
total=10
Total=20
TOTAL=30
4.The Maximum Lenght of Identifier Names are Unlimited.
5.Keywords are not used an Identifier Names.
eg:
a=10 (is valid)
if=10(is not valid)
6.In Python underscorer character is also treated as alphabet.
so may start or end with identifiers
we must use the underscorer character.
eg:
x = it is normal variable
_x = It is a Protected Variable
_ _ x = It is a Private Variable
_ _ x _ _ = It is a Magic Variable.

8.Reserved words/Keywords:

True False None

and or not is

if elif else

while for break continue return


in yield

try except finally raise


assert

import from as class def


pass

global nonlocal lambda del with

RULES FOR THE KEYWORDS:


1.Above all These are Alphabet Symbol.
2.Except the following 3,remaining all contains only lower
case Alphabets.(True,False and None)
Eg:
a=true (is not valid for bool)
a=True (is valid for bool)
3.switch and do-while statements are not used as Python
4.int,float,double,complex such type of keywords are not
required in python.
5.How to show the all keywords list in Python:
eg:import keyword
keyword.kwlist

9.Data Types

What are various type of data type:


it's totally 14 data types are availble in python

int list bytes


float tuple bytearray
complex set range
bool frozenset none
str dict

Note:Everything in python is an object data type not maintain


standard/primitive data's.
a=10
type(a)--it defines type of data.it is inbuilt function
id(a)--it defines address of that object.it is also inbuilt
function
print(a)--it print the inside the value of that variable.it is also
inbuilt function.
1)int data type:
this type of numbers also called as integral numbers or whole
numbers
long numbers are maintain with long data type
short int numbers are maintain with int data type
but these two types of data types are applicable in python2
note: all types of integer are maintain in python 3x with int data
type

---How to convert binary or octal or hexa decimal numbers in decimal


form:
how many ways we can represent integer values in PYTHON:
1.decimal form(base-10) (0-9) (eg:1111)
eg:1111 (it is valid)

2.binary form(base-2) (0 or 1) (eg:0b1111) if any number


prefix with 0b or 0B
eg: 1111 (it is not allowed)
0b1111(it is valid)

3.octal form(base-8) (0-7) (eg:0o123) if any number


prefix with 0o or 0O
eg: 0o786(it is not allowed in octal)
0o123 (it is valid)

4.hexa decimal form(base-16) (0-9 and A to F or a to f) if any


value prefix with ox or oX
eg:oX10=16(it is valid)
oxFace(it is valid)
oxBeef(it is valid)
oxBeer(it is not valid)

---How convert the integer values into one base to another base
(by using Base convertion Method)

Python Provide 3 inbuilt function for base convertion type

1.bin()-to convert from another base to binary base


eg:bin(15)-0b1111(decimal to binary)
eg:bin(0o123)-ob1010011(octal to binary)
eg:bin(oxFace)-0b11111010111001110(hexa to binary)
2.oct()-to convert from another base to octal
eg:oct(100)-0o144(decimal to oct)
eg:oct(0b111101)-0o75(binary to oct)
eg:oct(oxFace)-0o175316(octal to oct)
3.hex()-to convert from another base to hexa
eg:hex(1000)-ox3e8(decimal to hexa)
eg:hex(0b10111111)-oxbf(binary to hexa)
eg:hex(0o123456)-oxa72e(octal to hexa)

float data type:


f=12.456
type(f)<class 'float'>

f=1.234 its valid


f=0B1.1011-syntax error
f=0o123.456-syntax error
f=ox123.57-syntax error
note:floating point values are only represent only in the decimal
form not integral numbers
it also represent the exponential form/scientific form.
f=1.2e3 (this is exponential form or scientific notation)
o/p :print(f)-1200.03
1200000000000000=1.2e16
3.complex data type:it is a very special data type in python.in c,c++ or
java have not maintain this type.
if we want use scientific application,electrical eng
application,mathematical Application.

syntax: a+bj
a is real part
b is imaginary part
j2=-1
j=sqrt(-1)
eg:10+20j(valid)
10.5+20j(valid)
10.5+20.6j(valid)
eg:x=10+20j
print(type(x))-complex
print(x.real)-10.0
print(x.imag)-20.0
eg:0b1111+20j(it is valid)
20+0b1111j(it is not valid)
real part maintain binary or decimal or hexaform but imaginary form
inly maintain deciaml
eg:two complex numbers are also availble in arthametic
operations
x=10+20j
y=20+30j
print(x+y)
print(x*y)

4.bool data type:this data type represent logical True or False values
eg:b=True(valid)
type(b)-boolean
b=true(not valid)
--name true is error

eg: <<<a=10
<<<b=20
<<<c=a>b
<<<print (c)
<<<False
<<<type(c)
<<<class 'boolean'
eg: print(True+True) -2
print(True-False)- 1
print(True*False)-0

4.str data type:Any sequence of character it self is called string.


we can use either single quotes or double quotes are used in
python
single quotes are very recommended in python.
eg:'naresh'
"naresh"
s='a'(it is valid)
note:character constants are also availble in python. there is no
char type data in python.strings and characters are string type only.
s='a'
Triple quotes are also availble in strings.
eg:''' nice computer education'''
single and double quotes are maintain only single line statements.
only triple quotes are maintain in multiline statements.

TRIPLE QUOTES RULES


1)to define MULTILINE STRING LITERAL
eg:'''nice
computer
education'''
eg:'''nice
computer
education'''
2)to use single quotes and double quotes as normal characters in
our string.
eg:'class by 'naresh' is very good'(it not valid)
eg:"class by 'naresh' is very good"(it is valid)
eg:"class by "naresh" is very good"(it not valid)
eg:'class by "naresh" is very good'(it is valid)
eg:'classes by 'naresh' for "python" are very good'(it not
valid)
eg:'''classes by 'naresh' for "python" are very good'''(it is
valid)
3)to define doc string

Index:python support positive index and negative index also.


s='n a r e s h'
(0 1 2 3 4 5)
(-6,-5,-4,-3,-2,-1)
print(s[0])=n
print(s[3])=e
print(s[100])=string index out of range error
print(s[-1])=h

Slice Operator:meaning(one piece is called slice)


i have one string is there that string we want to saparate one
slice.

syntax: s[begin:end]
return substring (SLICE) from begin index to end-1 index
s[3:9]
eg:s='abcdefghijklmnopqrstuvwxyz'
print(s[3:9])=defghi
default value is begin index value:0 to start and end 9-1 eg:s[ :9]
default value is end index value:3 to end of string eg:s[3: ]
eg:[:]-total characters disply.

note: s[3:1000] never going raise index error


only print d to all character print.
note: s[5:1] empty string we are going to get

IMPORTANT FEATURES:

1.HOW TO FIRST CHARACTER INTO UPPERCASE.


s='naresh'
output=s[0].upper()+s[1: ]
print(ouput)
o/p:Naresh

2.HOW TO LAST CHARACTER INTO UPPERCASE.


s='naresh'
output=s[0:len(s)-1]+s[-1].upper()
print(output)
o/p:naresH

3.HOW TO FIRST AND LAST CHARACTER INTO UPPERCASES.


s='naresh'
output=s[0].upper()+s[1:len(s)-1]+s[-1].upper()
print(output)
o/p:NaresH

+ OPERATOR:it is applicable for strings


eg: s='nice'+'computers'
print(s)
o/p:nice computers(it is valid)
eg: s='nice'+'10'
print(s)
o/p:nice10(it is invalid)
note:both are should be strings
* operator:this is string repitation operator
eg: s='nice'*3(string*int)
print(s)
o/p:nicenicenice(it is valid)
eg: s=3*'nice'
print(s)
o/p:nicenicenice(it is also valid)
note: both are not should be strings
eg: s='nice'*'computer'(string*string)
print(s)
o/p:it is error
eg: print('#'*10)
print('nice')
print('#'*10)

NOTE: int,float, complex,bool and str these are fundamentals datatypes


long data type only used in python2.0 not in 3.0.
there is no char data type in python char values also we can
represent by using str type only.

Type Casting:It is a process to convert the data from one type to another
type
it is also called type coersion.
type casting function are 5 totally
1)int():to convert from other types to int type
eg:float to int
int(10.989)=10
eg:complex to int
int(10+20j)=type error
note:comple numbers are not convert to int type
eg:bool to int
int(True)=1
int(False)=0
eg:str to int(compalsery string internal contains only
integral value that should be specified base-10 only)
int('15')=15
int('0b1111')=error
int('12.5')=error

2)float():to convert from other type to float type


eg:int to float
float(15)=15.0
float(ob1111)=15.0
eg:complex to float
float(10+20j)=it is error
eg:bool to float
float(True)=1.0
float(False)=0.0
eg:str to float(should be specify only base-10)
float("10")=10.0
float("20.6")=20.6
float("0xFace")=error
float("durga")=error
3)complex():to convert from other type to complex type
eg:form-1(one argument function iam taking)
eg:integer to complex
complex(10)=10+oj
eg:binary to complex
comple(0b1111)=15+0j
eg:float to complex
complex(10.5)=10.5+0j
eg:bool to complex
complex(True)=1+0j
complex(False)=0+0j=0j
eg:str to complex
complex("10")=10+0j
complex("10.5")=10.5+0j
eg:form-2(two argument function iam taking)
eg:int to complex
complex(10,20)=10+20j
eg:float to complex
complex(10.5,20.6)=10.5+20.6j
eg:string to complex
complex("10","20")=error
only first value is applicable like string but second number
not allowed
complex(10,"20")=error
second argument should not be taken complex number
4)bool():to convert from other type to bool type
eg:int to bool
bool(10)=True
bool(0)=False
bool(-10)=True
eg:float to bool(0 is false and non-zero is true)
bool(10.5)=True
bool(0.0)=False
bool(0.1)=True
eg:string to bool:if it is string argument is empty bool() is
false otherwise true
bool('True')=True
bool('false')=True
bool('yes')=True
bool('no')=True
bool(' ')=False
eg:complex to bool
bool(0+0j)=False
bool(1+0j)=True

5)str():to convert from other type to string type


eg:int to str
str(10)='10'
str(0b1111)=15
eg:float to str
str(10.5)=10.5
eg:complex to str
str(10+20j)=10+20j
eg:bool to str
str('True')=True
str('False')=False
Type casting summary:
int float complex bool string
arguments arguments arguments arguments
arguments

int() ok ok no ok ok

float() ok ok no ok ok

complex() ok ok ok ok ok

bool() ok ok ok ok ok

str() ok ok ok ok ok

Fundamental data type vs IMMutability:


Immutable-(Non changeable):
Once we creates an object,we can not perform any changes in that
object
if we are trying to perform any changes,with those changes a new
object will be created.
this non changeble behaviour is called Immutable.
eg: x=10
print(id(x))=1872880544
x=x+1
print(id(x))=1872880560
note:Both id 's are different

Mutable-changeable:

---------------------------------------
COLLECTION RELATED DATA TYPE:

LIST:IF U WANT REPRESENT A GROUP OF VALUES ARE SINGLE ENTITY,


WHERE ORDER IS IMPORTENT,DUPLICATE VALUES ARE ALLOWED THAN WE SHOULD GO
FOR LIST

L=[10,'NARESH',20,10,30]

1)ORDER IS PRESERVED(WHICH ORDER WE GIVE THAT THE SAME ORDER IS DISPLAY)


2)DUPLICATE OBJECTS ARE ALLOWED
3)MUST MAINTAINS []
4)HETROGENEOUS OBJECTS ALLOWED(INT,STRINGS AND FLOAT VALUES ARE ALLOWED)
5)INDEXING & SLICING ALLOWED
PRINT(L[0]) O/P:10
PRINT(L[-1]) O/P:30
PRINT(L[1:4]) O/P:[NARESH ,20,10]
6)LIST IS GROWABLE IN NATURE
L=[] IT IS EMPTY
L.APPEND(10) INSERTION ORDER PRESERVED IN THAT LIST
L.REMOVE(10) DELECTION ORDER IS ALLOWED
7)LIST IS MUTABLE L[0]=7777 PRINT(L)
--------------------------------------
TUPLE: EXATLY SAME AS LIST EXCEPT THAT IT IS IMMUTABLE
READ ONLY VERSION OF LIST IS TUPLE
T=() EMPTY TUPLE
T=(10) IT IS NOT TUPLE IT IS INT
----------------------------------------
SET:
--ORDER IS NOT REQUIRED
--DUPLICATES ARE REQUIRED.ONLY UNIQE ELEMENTS ARE DISPLAY
--MUST MAINTAIN { }
--INDEXING CONCEPT AND SLICING CONCEPT ARE NOT ALLOWED
--HETRO GENEOUS OBJECTS ARE ALLOWED
--SET IS GROWABLE AND SET MUTABLE
EG:
S={10,20,30,40}
S.ADD(50)(SAME OF APPEND METHOD)
NOTE:APPEND VALUE IS ADD AT LAST BUt ADD VALUE IS ADD AT ANY
POSITION)
SO ADD METHOD IS REQUIRED TO SET FUNCTIONALITY.
PRINT(S)
S.REMOVE(30)
PRINT(S)
S1={1,2,3,4}
PRINT(TYPE(S1))
--S={} IT IS NOT SET IT IS EMPTY DICTINORY
CHECK:S={}
PRINT(TYPE(S))
DICT TYPE.
--S=SET()(THIS IS EMPTY SET)
PRINT(TYPE(S))

DIFFERENCES B/W LIST AND SET


LIST SET
ORDER IS PRESERVED IT IS NOT APPLICABLE
DUPLICATES ARE ALLOWED IT IS NOT ALLOWED
[] {}
EG:1
--S={10,20,10,'NARESH',30,40}
PRINT(S)
O/P:{10,20,'NARESH',30,40}(DUPLICATES ARE NOT APPLICABLE AND ORDER
IS NOT REQUIRED)
EG:2
PRINT(S[0])--TYPE ERROR
PRINT(S[1:4])-TYPE ERROR
EG:3
------------------------------------------------
FROZEN SET:EXATLY SAME AS SET EXCEPT IMMUTABLE
THIS IS SET
S={10,20,30,40}
S.ADD(50)
S.REMOVE(30)
PRINT(S)
O/P:{10,20,40,50}

THIS FROZENSET
S={10,20,30,40}
FS=FROZENSET(S)
PRINT(TYPE(FS))
FS.ADD(50) (ERROR)
FS.REMOVE(30)(ERROR)

TUPLE FROZENSET
ORDER IS ALLOWED ORDER IS NOT ALLOWED
DUPLICATES ARE ALLOWED IT IS ALLOWED
INDEX AND SLICE APPLICABLE IT IS NOT APPLICABLE
IT IS IMMUTABLE IT IS IMMUTABLE
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-----------------
DICT:IF WE WANT REPRESENT A GROUP OBJECTS AS KEYVALUES PAIRS THEN WE
REQUIRED TO GO FOR DICT
DICT MEANS-DICTIONARY

KEY VALUES PAIRS


ROLLNO -RELATED NAMES
MOBILE NO-CORRESPONDING ADDRESS

EG:
D={K1:V1,K2:V2,K3:V3}
D={100:'NARESH',200:'LALITHA',300:'CHINNI',400:'SUNNY'}
EG: D={}
IT IS EMPTY DICT
EG: D[KEY]='VALUES'
D[100]='NARESH'
D[200]='SUNNY'
PRINT(D)
O/P:{100:'NARESH',200:'SUNNY'}
NOTE:ORDER IS NOT REQUIRED IN DICT
DUPLICATE KEYS ARE NOT APPLICABLE BUT VALUES CAN BE DUPLICATES
D[100]='LALITHA(KEY IS NOT CHANGE ONLY VALUE IS CHANGE)
O/P:{100:'LALITHA',200:'SUNNY'}
IMPORTENT:
1.A GROUP OF KEY VALUE PAIRS
2.ORDER IS NOT APPLICABLE
3.DUPLICATE KEYS NOT ALLOWED BUT VALUES ARE DUPLICATE
4.HETROGENEOUS OBJECT ALLOWED
5.MUTABLE,INDEXING AND SLICING CONCEPTS THESE THINGS ARE NOT APPLICABLE
------------------------------------------------
RANGE DATA TYPE:IF WE WANT TO REPRESENT SEQUENCE OF NUMBERS(0-100 OR 100
TO 200)
EG:r=range(10)
print(type(r)) o/p:class 'range'
print(r) o/p:range(0,10)
note: don`t print the all values.if we want to print all values than go
for loops
eg: r=range(10)
for x in r:
print(x)
o/p:1 2 3 4 5 6 7 8 9

RULES FOR RANGE DATA TYPE:


1.SEQUENCE OF NUMBERS
2.RANGE(ONE ARGUMENT)FORM-1
RANGE(ARGUMENT-1,ARGUMENT-2)
RANGE(ARGUMENT-1,ARGUMENT-2,ARGUMENT-3)
3.ORDER,INDEX,SLICE OPERATIONS ARE AVAILBLE
4.ONCE WE CREATE SEQUENCE WE CONN`T CHANGE THE NUMBERS(IMMUTABLE)
form1:print range from 0 to n-1 we want to go for form1 concept.
syntax: range(n)
from 0 to n-1
r=range(10) #0-9
r=range(100) #0-99
r=range(n) #0-(n-1)
form2:print range from 1-100 (or) 100 to 200 (or) 300 to 400 than we go
for form2
syntax:range(begin,end)
begin to end-1
eg:r=range(1,10) #1 to 9
for x in r:
print(x)
eg:r=range(1,11) #1 to 10
for x in r:
print(x)
form3:range(begin,end,increment/decrement)
eg:r=range(1,21,1)
1,2,3,4,.....20
r=range(1,21,2)
1,3,5,7,9.....19
r=range(1,21,3)
1,4,7,10.....19

eg:range(20,1,-5)
20,15,10,5,..
NOTE: INDEXING AND SLICING CONCEPTS ARE APPLICABLE in range data type
index:
r=range(10,21) #10,11,12,13,14.....20
print(r[0])=10
print(r[-1])=20
so indexing is applicable in range data type
slicing:
eg:r=range(10,21)
r1=r[1:5]
for x in r1
print(x)
eg:r=range(10,21)
print(r[0])=10
print(r[1])=11

r[1]=1000
print(r[1])=error
note:once we create sequence range is not change.it is immutable.

-----------------------------------------------------------------
byte data type:IF WE Want to represent a group of byte values than we
have to go for byte data types
if we want to handle images,audio and video files.
note: in other languages arrays are there,in this data type bytes are
there
eg:1
l=[10,20,30,40]
b=bytes(l)
print(type(b))
o/p:class 'byte'

eg:2
l=[10,20,30,40]
b=bytes(l)
for x in b:
print(x)
o/p:10 20 30 40
1.values only from 0 to 255
l=[10,20,30,40,256]
b=bytes(l)
this is value error.
2.immutable
l=[10,20,30,40]
b=bytes(l)
print(b[0])
b[0]=77
it's not accepting because you can not change.
so it is immutable
3.indexing and slicing are there
-------------------------------------------------------------
Bytearray:byte and bytearray are same.only one different i.e. this is
mutable
l=[10,20,30,40]
b=bytearray(l)
print(type(b))
o/p class 'byte array'

eg:1
l=[10,20,30,40,256]
b=bytes(l)
print(type(b))
print(b[0])
print(b[1])
note:it is not accepting because range is b/w 0 to 255
eg:2
l=[10,20,30,40,255]
b=bytes(l)
print(type(b))
print(b[0])
print(b[-1])
o/p:10 255
eg:3
l=[10,20,30,40,255]
b=bytes(l)
b[0]=77
for x in b:
print(x)
o/p:77,20,30,40,255
---------------------
very importent notes:
--------------------
list-mutable
tuple-immutable
set-mutable
frozenset-immutable
dict-mutable
range-immutable
bytes-immutable
bytearray-mutable

none data type: none means nothing


no values associated
eg:
a=10 (a is pointing to 10 object)
if a=none(a is not pointong to any object)
eg:1
def f1():
return 10

x=f1()
print(x)
o/p:10
eg:2
def f1():
print('hello')

x=f1()
print(x)
o/p:none

note: none is also internally as object


a=None( a is pointing to none)
print(id(a)) (address of a)
print(type(a))
o/p: class 'none'

HOW MANY NONE OBJECTS ARE THERE IN PYTHON? ONLY ONE


EG:
a=None
b=None
c=None
def f1()
pass note:we won't to return any value we must use in
python pass
d=f1() (d is also None)
all values are represent same object that is None
proof:
print(a,b,c,d)
print(id(a),id(b),id(c),id(d))
------------------------------------------------------
Escape sequence characters:
\n =new line
\t =horizontal tab
\r =carriage return
\b =back space
\f =form feed
\' =single quote
\" =Double quote
\\ =back slash character

Comments:
// this is single line comments in java
/*---------------
---------------multiline comment in java*/

# this is single line comment in python


MULTILINE COMMENTS ARE NOT IN PYTHON
#LINE 1
#LINE 2
#LINE 3
NOTE: ''' THIS IS
NOT
MULTILINE
COMMENT
'''
THIS IS DOC STRING ONLY

CONSTANTS:CONSTANTS CONCEPTS NOT ACCEPT IN PYTHON.


BUT
MAX_LENGTH=10
MAX_VALUE=20

TYPES OF OPERATORS:-----------------------------------------
Labraries:a group of modules are called as library.
module==> a group of functions,variables,classes

modules are not directly availble,we must import that module

for mathematical fuctions we should go for math module

eg:1
import math
print(math.sqrt(16))
print(math.pi)

eg:2

Operators:
1.ARITHMETIC OPERATORS:
Addition Opearator +
Subtraction -
Multiplication *
Division /
Percentage %
special arithmetic operators
floor division operator //(division operator)
Exponent Operator ** (power operator)
eg:
a=10
b=2
print("a+b=",a+b) #12
print("a-b=",a-b) #8
print("a*b=",a*b) #20
print("a/b=",a/b) #5.0
print("a%b=",a%b) #0
print("a//b=",a//b) #5
print("a**b=",a**b) #100

Eg:
a=10.5
b=2
print("a/b=",a/b) #5.25
print("a//b=",a//b) #5.0
print("a**b=",a**b) #110.25

/ this operator always return float values


// this operator return either int or float

note: 'naresh'+'naga'=naresh naga


'naresh' * 3=nareshnareshnaresh
RELATIONAL OPERATORS:

relational operators => < > <= >=


equality operators => == and !=

we can also apply relational operators for string type values.


EG:2
a=10
b=20
print("a>b is",a>b) #F
print("a>=b is",a>b) #F
print("a<b is",a<b) #T
print("a<=b is",a<=b) #T

EG:2
a='naresh'
b='ravi'
print("a>b is",a>b) #F
print("a>=b is",a>b) #F
print("a>b is",a>b) #T
print("a>=b is",a>b) #T
NOTE:LENGTH IS NOT CONSIDIRED.IT IS GOING it CONSIDERED AS ALPHABET ORDER
ascii code values are checking.

EG:3
a=10
b=20
if(a>b):
print(" a is greater than b")
print(" a is greater than b")
print(" a is greater than b")
print(" a is greater than b")
else:
print("a is not greater than b")
print("a is not greater than b")
print("a is not greater than b")
print("a is not greater than b")
print("program is over")

note:indentations must be required

EG:4
10<20<30<40==TRUE(ALSO APPLICABLE)
10<20<35<3==FALSE
NOTE:IN JAVA AND C NOTE APPLICABLE

EQULITY OPERATORS: == AND !=

== for content comparision only. is not addresses comparision


(address comparion for is operator)
eg:
10==20 ==>FALSE
10!=20 ==>TRUE
10==TRUE==>FALSE
False==False==>True
10==20==30==40==>False
10==5+5==3+7==2*5==>True
'a'==97 ==>False
10==10.0==>True
10=='10'==>False(both are not compatible)
1==True ==>True
10.10==10.1==>True

LOGICAL OPERATORS:
boolean:
AND ==> IF BOTH ARGUMENTS ARE TRUE THEN ONLY TRUE
OR ==>IF ATLEAST ONE ARGUMENT IS TRUE THEN RESULT IS TRUE
NOT ==>

EG:
True and False ==>False
True or False ==>True
not True==> False
For non boolean Types:

0 means false
non-zero means True
Empty String always False
''==>False

1)x and y
if x evaluates to false then result is x otherwise return y
10 and 20 ==>20
0 and 20 ==>0
0 and 2000==>0
1 and 'naresh'==>'naresh'
0 and 'naresh'==>0

2)x or y
if x is evaluates to True then returns x otherwise return y
10 or 20==>10
0 or 20==>20
0 or 0 ==>0
0 or true==>True
3)not x
not ''==>True
not 0==>True
not 10==>False

BITWIZE OPERATORS:
&
|
^
~
<<
>>
note: << >> these are sIN hift operators

APPLICABLE ONLY FOR INT AND BOOLEAN


4&5==>VALID

& =>if both bits are 1 then only 1 oterwise 0


| =>if atleast one bit is 1 then 1 otherwise 0
^ =>x-or==>if both bits are different then 1 otherwise 0
~ =>bitwise complement operator
1==>0 and 0==>1
<< =>bitwize leftshift
>> =>bitwize rightshift

INPUT AND OUTPUT FUNCTIONS:


--------------------------------------
in python2.0: two input methods are there
raw_input()
input()

in python3.0: only one input method is having.

x=input("Enter something:")
Enter something:'naresh'
type(x)
<class 'str'>

x=input("Enter something:")
Enter something:10
type(x)
<class 'str'>

note : input values are maintain internally always string type values.

how to string values are converted into other data types:

string to int:int()
string to float:float()
string to bool:bool()

eg:
x=int(input("Enter First Number:"))
y=int(input("Enter Second Number:"))
print("the sum=",x+y)

eg:
print("the sum=",int(input("Enter First Number"))+int(input("Enter
Seconf Number")))

how to read emp data from the keyboard.it contains eno,ename,and eaddr

eno=int(input("Enter Employee Number:"))


ename=input("Enter Employee Name:")
esal=float(input("Enter Employee Salary:"))
eaddr=input("Enter Employee Address:")
married=bool(input("Enter Employee Marriage Status:[True/False]"))
print("please confirm information.....")
print("Employee Number:",eno)
print("Employee Name:",ename)
print("Employee Salary:",esal)
print("Employee Address:",eaddr)
print("Employee Marriage?",married)
how to read multiple values from the keyboard ina single line:
---------------------------------------------------------------
10 20
a,b=[int(x)for x in input("Enter 2 no:").split()]
print("the sum=",a+b)

#read to float values from keyboard which has specified with, separation
and print sum
10.2,10.6

a,b=[float(x)for x in input("Enter 2 float values:").split(',')]


print("the sum=",a+b)

10:20:30:40 (sum of 4 no)


a,b,c,d=[float(x)for x in input("Enter 4 input values:").split(':')]
print("the sum=",a+b+c+d)

eval():meaning is evaluate
-------
x=eval("10+20+30")
print(x)

ex=input("Enter some expression:")


result=eval(ex)
print("the Result:",result)

O/P: 10+30+50=90

EG:
x=eval(input("Enter some data:")
print(type(x))

o/p : enter some data:10


class 'int'
o/p : enter some data:10.5
class 'float'
o/p : enter some data:true
class 'boolean'
o/p : enter some data:[10,20,30]
class 'list'
o/p : enter some data:(10,20,30)
class 'tuple'
eg:2
x=eval(input("Enter some data:")
print(type(x))
for x1 in x:
print(x1)

o/p:enter some data:[10,20,30]


class 'list'
10
20
30

How to read 3 values at a time with eval():


-------------------------------------------
a,b,c=[eval(x)for x in input("Enter 3 values:").split(",")]
print(type(a))
print(type(b))
print(type(c))

command line arguments:


--------------------------------------
the arguments which are passing from command prompt .these arguments are
command line arguments.
eg:
d:\>py test.py 10 20 30 40

how to pass values:


argv====> it is a list type
argv variable is available from sys module
note: module means group of variables,methods and classes.
eg:1
from sys import argv
print(type(argv))
class 'list'

eg:2(test.py)
from sys import argv
print(argv)

d:\>py test.py 10 20 30 40
o/p:[test.py 10 20 30 40]

eg:3(test.py)
from sys import argv
print(argv[1:])
print(argv[0])
print(argv[1])

d:\>py test.py 10 20 30 40
o/p:10 20 30 40
Is there any way to print all element by skipping only middle element
from array?
eg:
from sys import argv
print("the number of commandline arguments:",len(argv))
print("the list of command line arguments:",argv)
print("command line argument one by one:")
for x in argv:
print(x)
print("slice operator result:",argv[1:3])

o/p:
c:\>py.test.py a b c d
the number of commandline arguments:5
the list of command line arguments:['test.py','a' 'b' 'c' 'd']
command line argument one by one:
test.py
a
b
c
d
slice operator result:['a','b']
#read a group of int values from the keyboard as cmd line argument and
print sum?

from sys import argv


args=argv[1:]
sum=0
for x in args:
n=int(x)
sum=sum+n
print("the sum:",sum)

o/p:
c:\>py.test.py 100 200 300
the sum=600

eg:
from sys import argv
print(argv[1])

c:\>py test.py naga naresh


o/p:naga

note:if u read total name must enclosed b/w the " " or """ """ not
maintain the '' or ''' '''

c:\> py test.py "naga naresh"


o/p:naga naresh

eg:
from sys import argv
print(argv[1]+argv[2])

c:\> py test.py 10 20
o/p:1020
note: cmd read string type values

OUTPUT STATEMENTS:
----------------------
print() function
form-1:
------
print() without any arguments

eg:
print("hello")
print()
print("good evening")
print("how r u")

form-2:
-------
print(string)

eg:
print("hello naresh")
print("hello \n naresh")
print("hello \t naresh")
print("hello"+"naresh") #both arguments should be strings
print("hello","naresh") # space will be added into the middle

form-3:
----------
print() with variable number of arguments:
------------------------------------------
i)var -arg

eg:
a,b,c=10,20,30
print("the values are:",a,b,c)

ii)sep attribute

eg:
a,b,c=10,20,30
print(a,b,c)
print(a,b,c,sep=',')
print(a,b,c,sep=':')

iii)print() with end attribute

eg:end=''
# next data will be print in same line

print("Hello",end='')
print("Students",end='')
print("python",end='')
print("Very easy",end='')

eg:
print(10,20,30,40,sep=':')
print(10,20,30,40,sep='-')

eg:
print(10,20,30,40,sep=':',end='...')
print(10,20,30,40,sep='-')

note:default values of sep and end


sep===> space
end===> new line character \n

eg:
l=[10,20,30,40]
t=(10,20,30,40)
s={10,20,30,40}
print(l,end='')
print(t,end='')
print(s)
print(l,t,s)# it is also use

iv)print(object)
print(formatted string)

%i==>int type
%d==>int type
%f==>float
%s==>str type
print("formatted string" %(variable list))

eg:
a,b,c=10,20,30
print("a value is %i" %a)
print("a value is %i and b value is %i" %(a,b))

name="Naresh"
l=[10,20,30,40]
print("hello %s the list is: %s"%(name,l))

v)print() function with replacement operators:


{}==>replacement operator

eg:
name='naresh'
salary=10000
gf="python"
print("Hello {0} your salary is{1} and your girl friend {2} is waiting"
.format(name,salary,gf))
print("Hello {} your salary is{} and your girl friend {} is waiting"
.format(name,salary,gf))
print("Hello {x} your salary is{y} and your girl friend {z} is waiting".
format(z=gf,y=salary,x=name))

Flow Controls:
--------------------

at run time in which order the statements are going to be executed is


decided by flow controls

these statements are 3 types:


1.conditionl statements/selection statements:

if x
option-1
else
option-2

if x
action-1
elif x
action-2
elif x
action-3

if
if-else
if-elif-else

2.iterative statements:
loops

for loop
while

3.Transfer Statements:
break
continue
pass

1.conditional statements:

1) indentations are must maintain.


2) if any condition must end with :

syntax:1
if(condition):
statement1
statement2

note:under if only statement 1 only

eg:
name=input("Enter name:")
if name=="naresh":
print("Hello naresh good morning")
print("Hello naresh good morning")
print("Hello naresh good morning")
print("how are u")

syntax:2
if(condition):
action-1
else:
action-2

eg:2
name=input("Enter name:")
if name=="naresh":
print("Hello naresh good morning")
else:
print("orey good morning")
print("how are u")

syntax:3
if-elif-else
if(condition):
action-1
elif (condition):
action-2
elif (condition):
action-3
else:
action4
eg:
brand=input("Enter your favourate brand:")
if brand=="RC":
print("this is children brand")
elif brand=="KF":
print("this is not mucj kick")
elif brand=="KO":
print("this iS TOO LIGHT")
elif brand=="FO":
print("BUY ONE GET ONE OFFER")
else:
print("other brands are not required")

#program to find biggest of 2 no from keyboard


n1=int(input("Enter First Number"))
n2=int(input("Enter Second No:"))
if n1>n2:
print("Bigger Number is:",n1)
else:
print("Bigger Number is:",n2)

o/p:12 45
45 is biggest number

#program to find biggest of 3 no from keyboard


n1=eval(input("Enter First Number"))
n2=eval(input("Enter Second No:"))
n3=eval(input("Enter Third No:"))
if n1>n2 and n1>n3:
print("Bigger Number is:",n1)
elif n2>n3
print("Bigger Number is:",n2)
else:
print("Biggest number is:",n3)

o/p:10.5 20.6 30.7


30.7 is biggest no

#wheather the given number is in b/w the 1 and 100

n=int(input("Enter number:")
if n>=1 and n<=100:
print("the number ", n, "is in between 1 and 100")
else:
print("the number",n,"is not in between 1 and 100")

#enter digit in b/w the 1 to 10 only


0==>ZER0
1==>ONE
10==>PLZ ENTER THE VALUE IN B/W 1 AND 10

PROGRAM:
n=int(input("Enter a digit from 0 to 9:"))
if n==0:
print("zero")
elif n==1:
print("One")
elif n==2:
print("Two")
elif n==3:
print("Three")
elif n==4:
print("Four")
elif n==5:
print("Five")
elif n==6:
print("Six")
elif n==7:
print("Seven")
elif n==8:
print("Eight")
elif n==9:
print("Nine")
else:
print("plz enter a number from 0 to 9 only")

2) ITERATIVE STATEMENTS:

If we want to execute a group of statements multiple times than we should


go for
Iterative statements

Python supports two types of iterative statements


1.for loop
2.while loop

i)for loop:
If we want to execute some action for every element present in some
sequence(it may be string or collection)
than we should go for -for loop

syntax:1 for x in sequence:


Body

syntax:2 for x in (first value,second value,increment/decrement):


Body

where sequence can be string or any collection.


Body will be executed for every element present in the sequence

eg:1 to print characters present in the given string

s="Naga Naresh"
for x in s:
print(x)
o/p:
N
a
g
a
N
a
r
e
s
h
Eg:2 To print characters present in the given String indexwise

s=input("Enter Some String:")


i=0
for x in s:
print("the characters present at",i,"index is:",x)
i=i+1
c:\1>py test.py
Enter some string:Naga Naresh
The character present at 0 index is:N
The character present at 1 index is:a
The character present at 2 index is:g
The character present at 3 index is:a
The character present at 4 index is:
The character present at 5 index is:N
The character present at 6 index is:a
The character present at 7 index is:r
The character present at 8 index is:e
The character present at 9 index is:s
The character present at 10 index is:h

Eg:3 to print hello 10 times


for x in range(10)
print("Hello")
Eg:4 to display numbers from 0 to 10
for x in range(11)
print(x)
Eg:5 to display odd numbers from 0 to 20
for x in range(21):
if(x%2!=0):
print(x)
Eg6: to display numbers from 10 to 1 in descending order
for x in range(10,0,-1)
print(x)
Eg:7 to print sum of numbers present inside list
list=eval(input("Enter List"))
sum=0
for x in list:
sum=sum+x
print("the sum=",sum)
o/p:c:\1>py.test.py
Enter list:[10,20,30,40]
The sum=100

ii) while loop:


If we want to execute a group of statements iteratively until some
condition false, then
we should go for while loop.

Syntax:

eg:to print numbers from 1 to 10 by using while loop


x=1
while x<=10:
print(x)
x=x+1
eg:2 to display the sum of n numbers

n=int(input("enter n value:"))
c=1
sum=0
while c<=n:
x=int(input("Enter a no:"))
sum=sum+x
c=c+1
print("total sum=",sum)

eg:write a program to prompt user to enter some name until entering


Naresh
name=""
while name!="Naresh":
name=input("Enter name:")
print("thanks for conformation")

Infinite loops:
--------------
i=0
while True:
i=i+1
print("Hello",i)

Nested Loops:
--------------
Some times we can take a loop inside another loop,which are also known as
nested loops.

for i in range(4):
for j in range(4):
print("i=",i," j=",j)
output:
c:\1>py test.py
i=0 j=0
i=0 j=1
i=0 j=2
i=0 j=3
i=1 j=0
i=1 j=1
i=1 j=2
i=1 j=3
i=2 j=0
i=2 j=1
i=2 j=2
i=2 j=3
i=3 j=0
i=3 j=1
i=3 j=2
i=3 j=3

eg:1
Write a Program to display *'s in right Angled traingled form

*
* *
* * *
* * * *
* * * * *

n=int(input("Enter no of rows:"))
for i in range(1,n+1):
for j in range(1,i+1):
print("*",end="")
print()

alternet way:
-------------
n=int(input("Enter number of rows:"))
for i in range(1,n+1):
print("*"*i)

eg:2
a Program to display *'s in Pyramid Style or also known as equilent
triangle
*
* *
* * *
* * * *
* * * * *
* * * * * *

n=int(input("Enter number of rows:"))


for i in range(1,n+1):
print(" "*(n-i),end="")
print("* "*i)

3) TRANSFER STATEMENTS:
-------------------------------------------

1)break:
we can use break statement inside loops to break loop execution based on
some condition.

for i in range(10):
if i==7:
print("processing is enough.....plz break")
break
print(i)

c:\1> py text.py
0
1
2
3
4
5
6
processing is enough .....plz break

Eg:
cart=[10,20,600,60,70]
for item in cart:
if item>500:
print("To place this order insurence must be required")
break
print(item)

c:\1> py test.py
10
20
to place this order insurence must be required

2.Continue:
---------------
we can use continue statement to skip current iteration and continue next
iteration.

Eg:1
To print odd numbers in the range 0 to 9
for i in range (10):
if i%2==0:
continue
print(i)
c:\1>py test.py
1
3
5
7
9

Eg:2
cart=[10,20,500,700,50,60]
for item in cart:
if item>=500:
print("we can not process this item:",item)
continue
print(item)

c:\1>py test.py
10
20
we can not processn this item:500
we can not process this item:700
50
60

eg:3
numbers=[10,20,0,5,0,30]
for n in numbers:
if n==0:
print("Hey how we can divide with zero....just skipping")
continue
print("100/{}={}".format(n,100/n)

output:
100/10=10.0
100/20=5.0
Hey how we can divide with zero....just skipping
100/5=20.0
Hey how we can divide with zero....just skipping
100/30=3.3333333333333333335

Loops with else Block:


--------------------------------
Inside loop execution, if break statement not execute,then only else part
will be executed.
else means loop with out break.

cart=[10,20,30,40,50]
for item in cart:
if item>=500:
print("We can not process this order")
break
print(item)

else:
print("Congrats.....all item processes successfully")

output:

10
20
30
40
50
congrats .....all items processed successfully

eg:
cart=[10,20,600,30,40,50]
for item in cart:
if item>=500:
print("We can not process this order")
break
print(item)

else:
print("Congrats.....all item processes successfully")

output:

10
20

we can not process this order.

WHAT IS THE DIFFERENCE B/W FOR LOOP AND WHILE LOOP IN PYTHON:
-------------------------------------------------------------------------
----------------------------------
1. WE CAN USE LOOPS TO REPEAT CODE EXECUTION
2. REPEAT CODE FOR EVERY ITEM IN SEQUENCE-> FOR LOOP
3. REPEAT CODE AS LONG AS CONDITION IS TRUE-> WHILE LOOP

HOW TO EXIT FROM THE LOOP? BY USING BREAK STATEMENT

HOW TO SKIP SOME ITERATIONS INSIDE LOOP? BY USING CONTINUE STATEMENT.

WHEN ELSE PART WILL BE EXECUTED WRT LOOPS? IF LOOP EXECUTED WITHOUT BREAK
3) pass statement:

pass is a keyword in python.


In our programming syntacticqally if block is required which won't do
anything then we
can define that empty block with pass keyword.

pass
It is an empty statement
It si null statement
it won,t do anything

Eg:if True:
Syntax Error:unexpected EOF while parsing
if True:pass-> valid

def m1():
SyntaxError:unexpected EOF while parsing

def m1():pass

Use case of pass:


Sometimes in the parent class we have to declare a function with empty
body and child class responsible to provide
proper implementation. Such type of empty body we can define by using
pass keyword.(It is something like abstract
method in java)

Eg:def m1():pass

for i in range(100):
if i%9==0:
print(i)
else:pass

c:\1>py test.py
0
9
18
27
36
45
54
63
72
81
90
99

del statement:
---------------

--del is keyword in python.


--After using a variable, It is highly recommendedn to delete that
variable if it is no longer
required, so that the corresponding object is eligible for garbage
collection.
--we can delete variable by using del keyboard.

Eg:
x=1
print(x)
del x

After deleting a variable we can not access that variable otherwise we


will get name error.

x=10
del x
print(x)

Name error: name 'x' is not defined.

Note:We can delete variables which are pointing to immutable objects.But


we cannot delete the elements present
inside immutable object.

s='naresh'
print(s)
del s->valid
dels[0]-> Type error:'str' object does not support item deletion.

DIFFERENCE BETWEEN DEL AND NONE:


--------------------------------

In the case del, the variable will be removed and we cannot access that
variable(unbind operation)

s='naresh'
del s
print(s)-> Name error:Name 's' is not defined.
But in the case of None assignment the variable won't be removed but the
corresponding object is eligible
for garbage collections(re bind operation).Hense after assignment with
None value,we can access that variable.

s='naresh'
s=None
print(s)-> None

-------------------------------------------------------------------------
---------------------------------------------------------

STRING DATA TYPE:

The most commenly used object in any project and in any programming
language is String only.Hense we should aware complete
information about String data type.

What is String:
--------------------
Any Sequence characters with in either single quotes or double quotes is
considered as a String.

Syntax:
s='naresh'
s="naresh"

Note:In most of other languages like C,C++,JAVA, a single character with


in single quotes is trated as char data type value.
But in python we are not having char data type.Hence it is treated as
String only.

Eg:
ch='a'
type(ch)
<class 'string'>

How to define Multi-Line String Literals?


--------------------------------------------------------
We can define multiline String literals by using triple single or double
quotes.

Eg:
s='''Naresh
software
solutions'''

we can also use triple quotes to use single quotes or double quotes as
symbol inside String literal.

1) s='This is 'single quote symbol'==>Invalid


2) s='This is \'single quote symbol'==>Valid
3) s="This is 'single quote symbol"==>Valid
4) s='This is "single quote symbol'==>Valid
5) s='The "Python Notes" by 'naresh'is very helpful'==>invalid
5) s="The "Python Notes" by 'naresh'is very helpful"==>invalid
5) s='The \"Python Notes\" by \'naresh\'is very helpful'==>Valid
5) s='''The "Python Notes" by 'naresh'is very helpful'''==>Valid

How to access cahracters of a String?


We can access characters of a String by using the fallowing ways.
1)by using index
2)by using slice operator
1)Accessing Characters by using Index:
------------------------------------
==>Python supports both +ve and -ve Index
==>+ve Index means Left to Right(Forward Direction)
==>-ve Index means Right to Left (Backward Direction)

Eg:s='Naresh'

>>>s='Naresh'
>>>s[0]
'N'

>>>s[-1]
'h'
>>>s[10]
Index error :String Index out of range

Note: If we are trying to access characters of a string with out of range


index then we will
get error saying :IndexError
EG:
Write a program to accept some string from the keyboard and display its
characters by Index wise
(both positive and negative Index)

s=input("Enter some String:")


i=0
for x in s:
print("The characters present at positive index{}and at negative
index{}is {}".format(i,i-len(s),x))
i=i+1

o/p:

Enter some String:Naresh


The characters present at positive index0and at negative index-6is N
The characters present at positive index1and at negative index-5is a
The characters present at positive index2and at negative index-4is r
The characters present at positive index3and at negative index-3is e
The characters present at positive index4and at negative index-2is s
The characters present at positive index5and at negative index-1is h

2)Accessing Characters by using slice operator:


-----------------------------------------------
Syntax: s[begin index:end index:step]

==> begin index: From where we have to consider slice(substring)


==> End index : We have to terminate the slice(substring) at endindex-1
==>step: Incremented Value

Note:
-----

==>If we are not specifying begin index then it will consider from
beginning of the string.
==>If we are not specifying end index then it will consider up to end of
the string.
==>The default value for step is 1.

>>>s="Learning Python is very very easy!!!"


>>>s[1:7:1]
'earnin'
>>>s[1:7]
'earnin'
>>>s[1:7:2]
'eri'
>>>s[:7]
'Learnin'
>>>s[7:]
'g Python is very very easy!!!'
>>>s[::]
'Learning Python is very very easy!!!'
>>>s[:]
"Learning Python is very very easy!!!"
>>>s[::-1}
'!!!ysae yrev yrev si nohtyP gninraeL'

Behaviour Of Slice Operator :


------------------------------------------
1)s[begin:end:step]
2)Step value can be either +ve or -ve
3)If +ve then it should be forward direction(left to right) and we have
to consider begin
to end -1
4)if -ve then it should be backward direction(right to left) and we have
to consider begin
to end +1

***Note:
--------
==> In the backward direction if end value is -1 then result is always
empty
==> In the forward direction if end value is 0 then result is always
empty

In Forward Direction:
---------------------
default value for begin:0
default value for end:Length of string
default value for step:+1

In backward direction:
------------------------------------
default value for begin:-1
default value for end:(length of string+1)

Note: Either forward or backward direction, we can take both +ve and -ve
values for begin and end index.

Slice Operator case study:


-------------------------------------
s='abcdefghij'
1)s[1:6:2]->'bdf'
2)s[::1]->'abcdefghij'
3)s[::-1]->'jihgfedcba'
4)s[3:7:-1]->"
5)s[7:4:-1]->'hgf'
6)s[0:10000:1]->'abcdefghij'
7)s[-4:1:-1]->'gfedc'
8)s[-4:1:-2]->gec'
9)s[5:0:1]->"
10)s[9:0:0]->Value error:slice step can not be zero
11)s[0:-10:-1]->"
12)s[0:-11:-1]->'a'
13)s[0:0:1]->"
14)s[0:-9:-2]->"
15)s[-5:-9:-2]->'fd'
16)s[10:-1:-1]->"
17)s[10000:2:-1]->'jihgfed'

Note: Slice operator never raises index error.

Mathematical operators for string:


-----------------------------------------------
We can apply the fallowing mathematical operators for strings:

1.+ operator for concatenation


2.* operator for repetition
==>print("nice"+"naresh")->nicenaresh
==>print("naresh"*2)->nareshnaresh
Note:
1)To use + operator for string,compulsory both arguments should be string
type.
2)To use * operator for strings,compulsory one argument should be string
and other argument should be int.

len() in-built Function:


------------------------
We can use len() function to find the number of characters present in the
string.
Eg:
s="Naresh"
print(len(s))->6

Eg:write a program to access each character of string in forward and


backward direction by using while loop?
s="Learning Python is very easy!!!"
n=len(s)
i=0
print("Forward direction")
while i<n:
print(s[i],end='')
i+=1
print("Backward direction")
i=-1
while i>=-n:
print(s[i],end='')
i=i-1

Alternative ways:
-------------------
s="Learning Python is very easy!!!"
print("Forward direction")
for i in s:
print(i,end='')
print("forward direction")
for i is s[::]:
print(i,end='')

print("backward direction")
for i in s[::-1]:
print(i,end='')

Checking Memberships:
-------------------------------------
We can check wheather the character or string is the member of another
string or not by using in and not operators.

s='naresh'
print('n' in s)->True
print('z' in s)-> False

s=input("Enter main String:")


subs=input("Enter sub string:")
if subs in s:
print(subs,"is found in main string")
else:
print(subs,"is not found in main string")
output:
-------
c:\1>py test.py
Enter main string:Nice computer education
Enter sub sgtring:Nice
Nice is found in main string

c:\1>py test.py
Enter main string:Nice computer education
Enter sub sgtring:python
python is not found in main string

Comparision of Strings:
-----------------------
We can use comparison operators(<,<=,>,>=) and equality operators(==,!=)
for strings.
Comparision will be performed based on alphabetical order.

s1=input("Enter First String:")


s2=input("Enter Second String:")
if s1==s2:
print("Both Strings are equal")
elif s1<s2:
print("First string is less than second string")
else:
print(First string is greater than second string")

output:
c:\1>py test.py
Enter First String:naresh
Enter second String:naresh
Both strings are equal

c:\1>py test.py
Enter First String:naresh
Enter second String:ravi
First string less than second string

c:\1>py test.py
Enter First String:naresh
Enter second String:anil
First string greater than second string

Removing spaces from the string:


--------------------------------
We can use the fallowing 3 methods

1)rstrip()==>to remove spaces at right hand side


2)lstrip()==> to remove spaces at left hand side
3)strip()==> to remove spaces both sides

city=input("Enter your city name:")


scity=city.strip()
if scity=='Hyderabad':
print("Hello Hyderabadi...Adab")
elif scity=='Chennai':
print("Hello Madrasi....Vanakkam")
elif scity=="Bangalore":
print("Hello Kannadiya...subhodhaya")
else:
print("your entered city is invalid")

Finding Substrings:
------------------------------
We can use the fallowing 4 methods
For forward direction:
----------------------
1) find()
2) index()

For backward direction:


-----------------------
1)rfind()
2)rindex()

1)find():
---------
Return index of first occurrence of the given substring. If it is not
available then we will get -1.

s="Learning Python is very easy"


print(s.find("Python"))#9
print(s.find("java")#-1
print(s.find("r"))#3
print(s.rfind("r"))#21

Note: By default find() method can search total string.we can also
specify the boundaries to search.

s.find(substring,begin,end)

it will always search from begin index to end-1 index

s="durgaravipavansiva"
print(s.find('a'))#4
print(s.find('a',7,15)#10
print(s.find('z',7,15)#-1

index():
--------
index() method is exatly same as find() method except that if the
specified substring is not available
than we will get Value Error.

s=input("Enter main String:")


subs=input("Enter sub string:")
try
n=s.index(subs)
expect ValueError:
print("sbstring not found")
else:
print("substring found")

output:
c:\1>py test.py
Enter main String:Learning python is very easy
Enter sub sgtring:python
substring found

c:\1>py test.py
Enter main String:Learning python is very easy
Enter sub sgtring:java
substring not found

Program to display all positions of substring in a given Main String:


----------------------------------------------------------------------
s=input("Enter main String:")
subs=input("Enter sub string:")
flag=False
pos=-1
n=len(s)
while True:
pos=s.find(subs,pos+1,n)
if pos==-1:
break
print("Found at position",pos)
flag=True
if flag==False:
print("Not Found")

c:\1>py test.py
Enter main String:abbabababacdefg
Enter sub string:a
Found at position 0
Found at position 3
Found at position 5
Found at position 7
Found at position 9

c:\1>py test.py
Enter main String:abbaaabababababa
Enter sub string:bb
Found at position 1

Counting Substring in the given string:


---------------------------------------
We can find the number of occurrences of substring present in the given
string by using
count() method.

1)s.count(substring)->it will search through out the string


2)s.count(substring,begin,end)-> it will search from begin index to end-
1 index.

s="abcabcabcabcadda"
print(s.count('a'))
print(s.count('ab'))
print(s.count('a',3,7))

output:
6
4
2

Replacing a String with another String:


-----------------------------------------------------
s.replace(oldstring,newstring)
inside s,every occurence of old string will be replaced with new string.

Eg:1
s="Learning python is very difficult"
s1=s.replace("difficult","easy")
print(s1)

output:Learnign Python is very easy

Eg:2
s="abababababababab"
s1=s.replace("a","b")
print(s1)

output:bbbbbbbbbbbbbbb

String objects are immutable then how we change the content by using
replace() Method:
-------------------------------------------------------------------------
-------------
==> Once we create string object,we can not change the content.This non
changeable behaviour is nothing but Immutability.
If we are trying to change the content by using
any method,then with those changes a new objects will be created and
changes won't be happened in existing object.
==>Hence with replace() method also a new object got created but existing
object won't be changed.

Eg:3
s="abad"
s1=s.replace("a","b")
print(s,"is available at:",id(s))
print(s1,"is available at:",id(s1))

output:
abad is available at:4568672
bbbb is available at:4568704

In the above example, original object is available and we can usee new
object which was created because of replace() method.

Splitting of Strings:
---------------------
We can split the given string according to specified seperator by using
split() method.
l=s.split(seperator)
The default seperator is space.The return type of split() method is List.

Eg:1
s="Nice Computer Education"
l=s.split()
for x in l:
print(x)
output:
Nice
Computer
Education

Eg:2
s="22-02-2019"
l=s.split('-')
for x in l:
print(x)

output:
22
02
2019

Joining of Strings:
-------------------
We can join a Group of Strings(List OR Tuple) wrt the given Seperator
s=seperator.join(group of strings)

Eg:1
t=('sunny','bunny','chinny')
s='-'.join(t)
print(s)

output:sunny-bunny-chinny

Eg:2
l=['Hyderabad', 'singapore','london','dubai']
s=':'.join(l)
print(s)

output: Hyderabad:singapore:london:dubai

Changing case of a String:


--------------------------
We can change case of a String by using the following 5 methods.

1)upper()->To convert the all characters into uppercase


2)lower()->to convert the all characters into lowercase
3)swapcase()-> to convert the all lowercase into uppercase and all
uppercase characters into lowercase.
4)title()->To convert the all character to title case.i.e first character
is every word should be uppercase
and all remaining characters are should be in lowercase.
5)capitalize()->Only first character will be converted into uppercase and
all remaining characters can be converted to lowercase.

Eg:1
s="learning Python is very Easy"
print(s.upper())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.capitalize())

output:
LEARNING PYTHON IS VERY EASY
learning python is very easy
LEARNING pYTHON IS VERY eASY
Learning Python Is Very Easy
Learning python is very easy

Checking Starting and Ending part of the String:


------------------------------------------------
Python contains the fallowing methods for this purpose
1)s.startswith(substring)
2)s.endswith(substring)
s='learning python is very easy'
print(s.startswith('learning'))
print(s.endswith('learning'))
print(s.endswith('easy'))

output:
-------
True
False
True

To check the type of characters present in a string:


----------------------------------------------------
Python contains the fallowing methods for this purpose.

1)isalnum():Returns True if all characters are alphanumaric(atoz,ATOZ,


0to 9)
2)isalpha():Returns True if all characters are only alphabet
symbols(atoz,AtoZ)
3)isdigit():Returns True is all characters are digits only(0-9)
4)islower():Returns True if all characters are only lowercase alphabet
symbols
5)isupper():Returns True if all characters are only uppercase alphabet
symbols
6)istitle():Returns True if string is in title case
7)isspace():Returns True if string contains only spaces.

Eg:
print('Naresh786'.isalnum())->True
print('naresh786'.isalpha())->False
print('naresh'.isalpha())->True
print('naresh'.isdigit())->False
print('786786'.isdigit())->True
print('abc'.islower())->True
print('Abc'.islower())->False
print('abc123'.islower())->True
print('ABC'.isupper())->True
print('Learning Python is very easy'.istitle())->False
print("Learnign Python Is Is Very Easy'.istitle())->True
print(' '.isspace())->True

Demo Program:
-------------
s=input("Enter any character:")
if s.isalnum():
print("Alpha Numaric Charatcter")
if s.isalpha():
print("Alphabet character")
if s.islower():
print("Lowercase Alphabet Charatcter")
else:
print("UPPER CASE ALPHABET CHARACTER")
else:
print("It is a digit")
elif s.isspace():
print("It is a space character")
else:
print("Non space special character")

c:\1>py test.py
Enter any character:7
Alpha Numaric Charatcter
It is a digit

c:\1>py test.py
Enter any character:a
Alpha Numaric Charatcter
Alphabet character
Lowercase Alphabet Charatcter

c:\1>py test.py
Enter any character:$
Non space special character

c:\1>py test.py
Enter any character:A
Alpha Numaric Charatcter
Alphabet character
UPPER CASE ALPHABET CHARACTER

-------------------------------------------
Formating the strings:
We can format the strings with variable values by using replacement
operator{} and format() method.

name='naresh'
salary=10000
age=28
print("{}'s salary is {} and his age {}".format(name,salary,age))
print("{0}'s salary is{1} and his age{2}".format(name,salary,age))
print("{x}'s salary is{y} and his age{z}".format(z=age,y=salary,x=name))

output:
naresh's salary is 10000 and his age 28
naresh's salary is10000 and his age28
naresh's salary is10000 and his age28

IMPORTANT PROGRAMS REGARDING STRING CONCEPTS:

1)Write a program ro reverse the given string:


Input:naresh
output:hseran

1st way:
--------
s=input("Enter some string")
print(s[::-1])
2nd way:
--------
s=input("Enter some string")
print(''.join(reversed(s)))
3rd way:
--------
s=input("Enter some string:")
i=len(s)-1
target="
while i>=0:
target=target+s[i]
i=i-1
print(target)

2)write a program to reverse order of words:

Input:Learning Pythonis very Easy


output:Easy Very is Python Learning

s=input("Enter some string:")


l=s.split()
l1=[]
i=len(l)-1
while i>=0:
l1.append(l[i])
i=i-1
output=''.join(l1)
print(output)

output:
-------
Input:Learning Pythonis very Easy
output:Easy Very is Python Learning

3) write a program to reverse internal content of each word:

Input:Nice Computer Education


output:eciN retupmoC noitacudE

s=input("Enter some String:")


l=s.split()
l1=[]
i=0
while i<len(l):
l1.append(l[i][::-1])
i=i+1
output=''.join(l1)
print(output)

4)write a program to print charatcers at odd position and even position


for the given string?

1st way:
--------
s=input("Enter Some String:")
print("Charatcers at even position:",s[0::2])
print("Characters at odd position:",s[1::2])

2nd way:
--------
s=input("Enter some string:")
i=0
print("Character at even position:")
whiel i<len(s):
print(s[i],end=',')
i=i+2
print()
print("Characters at odd Position:")
i=1
while i<len(s):
print(s[i],end=',')
i=i+2

5)Program to merge characters of 2 strings into a single string by taking


characters alternatively

Input: s1="ravi"
s2="teja"
output: rtaevjia

s1=input("Enter First String:")


s2=input("Enter SeconD String:")
output=''
i,j=0,0
while i<len(s1) or j<len(s2)
if i<len(s1):
output=output+s1[i]
i+=1
if j<len(s2):
output=output+s2[j]
j+=1
print(output)

6)
write a program to sort the characters of the string and First alphabet
symbols followed by numaric values:

Input:B4A1D3
output:ABD134

s=input("Enter First String:")


s1=s2=output=''
for x in s:
if x.isalpha():
s1=s1+x
else:
s2=s2+x
for x in sorted(s1):
output=output+x
for x in sorted(s2):
output=output+x
print(output)

7)a program for the fallowing requirement


Input:a4b3c2
Output:aaaabbbcc

s=input("Enter First String:")


output=''
for x in s:
if x.isalpha():
output=output+x
previous=x
else:
output=output+previous*int(x)-1)
print(output)

Note:chr(unicode)->the corresponding character


ord(character)-> the corresponding unicode value

8)write a program to perform fallowing activity


INput:a4k3b2
output:aeknbd

s=input("Enter some string:")


output=''
for x in s:
if x.isalpha():
output=output+x
previous=x
else:
output=output+chr(ord(previous)+int(x))
print(output)

9)write a program to remove duplicates characters from the given input


string:

Input:ABCDABBCDABBBCCCDDEEEF
output:ABCDEF

s=input("Enter some String:")


l=[]
for x in s:
if x not in l:
l.append(x)
output=".join(l)
print(output)

10)
write a program to find the number of occurrences of each character
present in the given string:

Input:ABCABCABBCDE
output:A-3,B-4,C-3,D-1,E-1

s=input("Enter some string:")


d={}
for x in s:
if x in d.keys():
d[x]=d[x]+1
else:
d[x]=1
for k,v in d.items():
print("{}={}Times".format(k,v))

11)
write a program to perform the fallowing task:

input:'one two three four five six seven'


output:'one owt three ruof five xis seven'

s=input("Enter some string:")


l=s.split()
l1=[]
i=0
while i<len(l):
if i%2==0:
l1.append(l[i])
else:
l1.append(l[i][::-1]
i=i+1
output=''.join(l1)
print('original string:',s)
print('output string:',output)

Formatting the strings:


------------------------------------
We can format the strings with variable values by using replacement
operator {} and
format() method
The main objective of format() method to format string into meaningful
output form.

Case-1:Basic formatting for default,positional and keyboard arguments.


------

Formating the strings:


We can format the strings with variable values by using replacement
operator{} and format() method.

name='naresh'
salary=10000
age=28
print("{}'s salary is {} and his age {}".format(name,salary,age))
print("{0}'s salary is{1} and his age{2}".format(name,salary,age))
print("{x}'s salary is{y} and his age{z}".format(z=age,y=salary,x=name))

output:
naresh's salary is 10000 and his age 28
naresh's salary is10000 and his age28
naresh's salary is10000 and his age28

Case:2:Formatting Numbers
------
d->Decimal Number
f->Fixed point number(float).The default precision is 6
b->Binary format
o->octal Format
x->Hexa Decimal Format(Lower Case)
X->Hexa Decimal Format(Upper case)

Eg:1
print("The integer Number is:{}".format(123))
print("The integer Number is:{d}".format(123))
print("The integer Number is:{:5d}".format(123))
print("The integer Number is:{:05d}".format(123))

Output:
The integer Number is:123
The integer Number is:123
The integer Number is: 123
The integer Number is:00123

Eg:2
print("The float number is:{}".format(123.4567))
print("The float number is:{:f}".format(123.4567))
print("The float number is:{:8.3f}".format(123.4567))
print("The float number is:{:08.3f}".format(123.4567))
print("The float number is:{:08.3f}".format(123.45))
print("The float number is:{:083f}".format(786786123.45))

output:

The Float Number is:123.4567


The Float Number is:123.456700
The Float Number is: 123.457
The Float Number is:0123.457
The Float Number is:0123.450
The Float Number is:786786123.450

NOTE:
1.{:08.3f}
2.Total positions should be minimum 8
3.After decimal point exactly 3 digits are allowed.If it less then 0s
will be placed in the last positions
4.If total number<8 positions then 0 will be placed MSBs
5.if total number>8 positions then all integer digits will be considered.
6.The extra digit we can take only 0.

Note:for number default alignment is Right Alignment(>)

Eg:3
print Decimal value in binary, octal and hexadecimal form

print("Binary Form :{0:b}".format(153))


print("octal form :{0:o}".format(153))
print("Hexa decimal Form:{0:x}".format(154))
print("Hexa decimal Form:{0:X}".format(154))

output:
Binary Form:10011001
Octal Form:231
Hexa decimal Form:9a
HexaDeciaml Form:9A

Note:We can Represent only int values in binary,octal and hexadecimal and
it is not possible for float values.

Note:
1){:5d} it takes an integer argument and assigns a minimum width of 5.
2){:8.3f} it takes a float argument and assigns a minimum width of 8
including"."and after
decimal point exactly 3 digits are allowed with round operation if
required
3){:05d} the blank spaces can be filled with 0.In this place only 0
allowed.

Case:3
Number Formating for signed numbers.
1.While displaying positive numbers,If we want to include + then we have
to write
{:+d} and {:+f}

2.Using plus for -ve numbers there is no use and for -ve number -sign
will come automatically.

print("int value with sign:{:+d}".format(123))


print("int value with sign:{:+d}".format(-123))
print("int value with sign:{:+f}".format(123.456))
print("int value with sign:{:+f}".format(-123.456))

Output:
Int value with:+123
Int value with sign:-123
Float value with sign:+123.456000
Float value with sign:-123.456000

Case:4 Number Formatting with Alignment

1) <,>,^ and = are used for alignment


2) < --> Left Alignment to the remaining space
3) ^ --> Center Alignment to the remaining space
4) > --> Right Alignment to the remaining space
5) = --> Forces the signed (+)(-) to the left most position

Note:Default alignment for numbers is Right Alignment

Eg:
print("{:5d}".format(12))
print("{:<5d}".format(12))
print("{:<05d}".format(12))
print("{:>5d}".format(12))
print("{:>05d}".format(12))
print("{:^5d}".format(12))
print("{:=5d}".format(-12))
print("{:^10.3f}".format(12.23456))
print("{:=8.3f}".format(-12.23456))

Output:
12
12
12000
12
12
00012
12
-12
12.235
-12.235

Case:5 String Formating with format() method.


similar to numbers, we can format string values also with format()
method.
s.format(string)

print("{:5d}".format(12))
print("{:5}".format("rat"))
print("{:>5}".format("rat"))
print("{:<5}".format("rat"))
print("{:^5}".format("rat"))
print("{:*^5}".format("rat")) #instead of * we can use any
character(like +,$,a etc)

Output:
12
rat
rat
rat
rat
*rat*

Note: For numbers default alignment is right where as for string default
alignment is left

Case:6
Truncating String with format() method

print("{:.3}".format("nicesoftware"))
print("{:5.3}".format("nicesoftware"))
print("{:>5.3}".format("nicesoftware"))
print("{:^5.3}".format("nicesoftware"))
print("{:*5.3}".format("nicesoftware"))

output:
nic
nic
nic
nic
*nic*

Case7:Formatting dictionary members using format()

person={'age':48,'name':'durga'}
print("{p[name]}'s age is:{p[age]}".format(p=person))

Output:
durga's age is:48
Note: p is alias name of dictionary
person dictionary we are passing as keyboard argument

more convinient way is to use **person

person={'age':28,'name':'naresh'}
print("{name}'s age is :{age}".format(**person))

Output:
Naresh age is:28

Case:8
Formatting class members using format()
class person:
age=28
name="naresh"
print("{p.name}' age is :{p.age}".format(p=person()))

Output:naresh's age is:28

class Person:
def__init__(self,name,age):
self.name=name
self.age=age
print("{p.name}'s age is:{p.age}".format(p=Person('naresh',28)))
print("{p.name}'s age is:{p.age}".format(p=Person('Ravi',50)))

Note:
Here person object is passed as keyword argument .We can access by using
its refference
variable in the template string.

Case:9
Dynamic Formatting using format()

string="{:{fill}{align}{width}}"
print(string.format('cat',fill='*',align='^',width=5))
print(string.format('cat',fill='*',align='^',width=6))
print(string.format('cat',fill='*',align='<',width=6))
print(string.format('cat',fill='*',align='>',width=6))

Output:
*cat*
*cat**
cat***
***cat

Case:10
--------
Dynamic Float format template

num="{:align}{width}.{precision}f}"
print(num.format(123.236,align='<',width=8,precision=2))
print(num.format(123.236,align='>',width=8,precision=2))

Output:
123.24
123.24

Case:11
-------
Formating Date Values

import datetime
#datetime formatting
date=datetime.datetime.now()
print("it 's now:{:%d/%m/%Y %H:%M:%S}".format(date))

output: it's now:19/03/2019 12:36:26

Case:12 Formatting complex numbers

complexNumber=1+2j
print("Real Part:{0.real} and imaginary
Part:{0.imag}".format(complexNumber))

Output:Real Part:1.0 and Imaginary Part :2.0

LIST DATA STRUCTURES:


---------------------
If we want to represent a group of individual objects as a single entity
where insertion
order preserved and duplicates are allowed,then we should go for List.
Insertion order preserved.
duplicate objects are allowed.
heterogeneous objects are allowed.
List is dynamic because based on our requirement we can increase the size
and decrease the size.
In List the elements will be placed with in square brackets and with
comma seperator.
we can differentiate duplicate elements by using index and we can
preserve insertion order by using index,Hence
index will play very important role.
Python supports both positive and negative indexex,+ve index means from
left to right where as negative index means right to left.
[10,"A","B",20,30,10]

-6 -5 -4 -3 -2 -1
10 A B 20 30 10
0 1 2 3 4 5

List objects are mutable.i.e we can change the content.

CREATION OF LIST OBJECTS:

1)We can create empty list objects as fallows.....


list=[]
print(list)
print(type(list))

[]
<class 'list'>

2)If we know elements already then we can create list as follows


list=[10,20,30,40]

3)with dynamic input:


list=eval(input("Enter List:"))
print(list)
print(type(list))

c:\1>py test.java
Enter List:[10,20,30,40]
[10,20,30,40]
<class,'list'>

4)with List Function:


---------------------
l=list(range(0,10,2))
print(l)
print(type(l))

c:\1>py test.py
[0,2,4,6,8]
<class 'list'>

Eg:1
s="naresh"
l=list(s)
print(l)
c:1>py test.py
['n','a','r','e','s','h']

5)With Split Functions

s="Learning Python is very very easy"


l=s.split()
print(l)
print(type(l))

c:1>py test.py
['Learning','python','is','very','very','Easy']

Note:Some time we can take list inside another list, such type of list
are called nested lists.
[10,20,[30,40]]

ACCESSSING ELEMENTS OF LIST:


----------------------------
We can access elements of the list either by using index or by using
slice operator(:)

1)by using index:


-----------------
List fallows zero based index.ie index of first element is zero.'
List support both +ve and -ve indexes
+ve index meant for Left to Right.
-ve Index meant for Right to Left.
list=[10,20,30,40]

-4 -3 -2 -1
10 20 30 40
0 1 2 3

print(list[0])->10
print(list[-1])->40
print(list[10])->Index error : list index out of range

2)by using slice operator:


--------------------------
Syntax: list2=list1[start:stop:step]

start->It indicates the Index where slice has to start default value is
0.
stop-> It indicates the Index where slice has to End Default Value is max
allowed Index of List ie Length of the List
Step->increment value
Default Value is 1

n=[1,2,3,4,5,6,7,8,9,10]
print(n[2:7:2])
print(n[4::2])
print(n[3:7])
print(n[8:2:-2])
print(n[4:100])

output:
c:1>py test.py
[3,5,7]
[5,7,9]
[4,5,6,7]
[9,7,5]
[5,6,7,8,9,10]

List vs Mutability:
-------------------
Once we creates a List object,We can modify its content.Hence List
objects are mutable.
n=[10,20,30,40]
print(n)
n[1]=777
print(n)

c:1>py test.py
[10,20,3,40]
[10,777,30,40]

Traversing the Elements of List:


--------------------------------

1) By using while loop:


-----------------------
n=[0,1,2,3,4,5,6,7,8,9,10]
i=0
while i<len(n):
print(n[i])
i=i+1
c:1> py test.py
0
1
2
3
4
5
6
7
8
9
10

2)By using for loop:


--------------------
n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
print(n1)
c:1>
0
1
2
3
4
5
6
7
8
9
10
3)To display only Even Numbers:
-------------------------------
n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
if n1%2==0:
print(n1)

c:1>py test.py
0
2
4
6
8
10

4)To display Elements by index wise:


------------------------------------
l=["A","B","C"]
x=len(l)
for i in range(x):
print(l[i],"is available at positive index:",i,"and at negative
index:",i-x)

c:1>py test.py
A is available at positive index:0 and at negative index:-3
B is available at positive index:0 and at negative index:-2
C is available at positive index:0 and at negative index:-1

Importent Functions Of List:


----------------------------

I. TO GET Information about List:

1)len():Returns the number of elements present in the list.


eg:
n=[10,20,30,40]
print(len(n))->4

2)count():It returns the number of occurences of specified item in the


list

n=[1,2,2,2,2,3,3]
print(n.count(1))
print(n.count(2))
print(n.count(3))
print(n.count(4))

o/p:.append
c:1>py test.py
1
4
2
0

3)index():Returns the index of first occurence of the specified item.


n=[1,2,2,2,2,3,3]
print(n.index(1))->0
print(n.index(2))->1
print(n.index(3))->5
print(n.index(4))->Value Error :4 is not list
Note:If the specified element not present in the then we will get
ValueError.Hence
before index() method we have to check whether item present in the or not
by using in
operator.
print(4 in n)->false

II.MANUPLATING ELEMENTS OF LIST:


--------------------------------
1)append() Function:
We can use append() function to add item at the end of the list.

list=[]
list.append("A")
list.append("B")
list.append("C")
print(list)

c:\1>py test.py
['A','B','C']

Eg:To add all elements to list up to 100 which are divisible by 10


list[]
for i in range(101):
if i%10==0:
list.append(i)
print(list)

c:\1>py test.py
[0,10,20,30,40,50,60,70,80,90,100]

2)insert() Function:
To insert item at specified index position

n=[1,2,3,4,5]
n.insert(1,888)
print(n)

c:\1>py test.py
[1,888,2,3,4,5]

eg:1

n=[1,2,3,4,5]
n.insert(10,777)
n.insert(-10,999)
print(n)

c:\1>py test.py
[999,1,2,3,4,5]
[999,1,,2,3,4,5,777]

Note:If the specified index is greater than max index then element will
be inserted at last position.If the specified index is smaller than
element will be inserted at
first position.

Difference between append() and index()


-----------------------------------------
append() insert()
In list when we add any element it will In list we can
insert any element in particular index
come in last i.e. it will be last element. number

3) extend() Function:
---------------------
To add all items of one list to another list.
l1.extends(l2)
all items present in l2 will be added to l1

order1=["Chicken","Mutton","Fish"]
order2=["RC","KF","FO"]
order1.extend(order2)
print(order1)

c:1\>py test.py
['Chicken','Mutton','Fish','RC','KF','FO']

order=["Chicken","Mutton","Fish"]
order.extend("Mushroom")
print(order)

c:1>py test.py
["Chicken",Mutton","Fish","M","u","s","h","r","o","o","m"]

4)remove() Function:
--------------------
We can use this function to remove specified item from the list.If the
item present multiple times
then only first occurence will be removed.

n=[10,20,10,30]
n.remove(10)
print(n)

c:1>py test.py
[20,10,30]

If the specified item not present in list then we will get ValueError.

n=[10,20,10,30]
n.remove(40)
print(n)

ValueError:list.remove(x):x not in list

Note:Hence before using remove() method first we have to check specified


element
present in the list or not by using in operator.

5)pop() Function:
----------------
It removes and returns the last element of the list.
This is only function which manipulate list and returns some element.

n=[10,20,30,40]
print(n.pop())
print(n.pop())
print(n)
c:1>py test.py
40
30
[10,20]

If the list is empty then pop() function raises index error

n=[]
print(n.pop())->index error:pop from empty list

Note:
1)pop() is the only function which manipulates the list and returns some
value
2)In general we can use append() and pop() functions to implement stack
datastructure
by using list,which follows LIFO(Last in first out) order.

In general we can use pop() function to remove last element of the list.
but we can use to remove
elements based on index.

n.pop(index)->To remove and return element present at specified index.


n.pop()->To remove and return last element of the list

n=[10,20,30,40,50,60]
print(n.pop())->60
print(n.pop(1))->20
print(n.pop(10))-> Index error :pop index out of range

DIFFERENCE B/W REMOVE() AND POP()

remove() pop()
We can use to remove special element We can use to remove last
element
from the list from the list
It can return any value. It return removed element
If special element not available then If List is empty then we get
Error
we get Value Error

Note:List Objects are dynamic.i.e. based on our requirement we can


increase and decrease the size.

append(),insert(),extend()->for increasing the size /growable nature


remove(),pop()-> for decreasing the size / shrinking nature

III) Ordering Elements of List:


-------------------------------

1)reverse():
------------
We can use to remove() order of elements of list.

n=[10,20,30,40]
n.reverse()
print(n)

c:1>pt test.py
[40,30,20,10]
2)sort():
---------
In list by default insertion order is preserved.If we want to sort the
elements of list according to default
natural sorting order then we should go for sort() method.

for numbers->Default Natural sorting Order is Ascending Order.


for Strings->Default Natural sorting order is Alphabetical Order

n=[20,5,15,10,0]
n.sort()
print(n)->[0,5,10,15,20]

s=["Dog","Banana","Cat","Apple"]
s.sort()
print(s)->['Apple','Banana','Cat','Dog']

Note:To use sort() function,compulsory list should contain only


homogeneous elements.
Otherwise we will get TypeError.

n=[20,10,"A","B"]
n.sort()
print(n)
Type Error:'<' not supported between instance of 'str' and 'int'.

Note:In Python 2 if list contains both numbers and Strings then sort()
functions first sort
numbers followed by strings.

n=[20,"B",10,"A"]
n.sort()
print(n)#[10,20,'A','B']

But in Python 3 it is invalid.

TO Sort in Reverse of Default Natural Sorting Order:


----------------------------------------------------
We can sort accoerding to reverse of default natural sorting order by
using reverse=True argument.

n=[40,10,30,20]
n.sort()
print(n)->[10,20,30,40]
n.sort(reverse=True)
print(n)->[40,30,20,10]
n.sort(reverse=False)
print(n)->[10,20,30,40]

Aliasing and Closing of List Objects:


--------------------------------------
The process of giving another reference variable to the existing list is
called aliasing.

x=[10,20,30,40]
y=x
print(id(x))
print(id(y))
The problem in this approach is by using one reference variable if we are
changing content,
then those changes will be reflected to the other reference variable.

x=[10,20,30,40]
y=x;
y[1]=777
print(x)->[10,77,30,40]

To overcome this problem we should go for cloning.


The process of creating exacttly duplicate independent object is called
cloning.

We can implement cloning by using slice operator or by using copy()


function.

1)By using Slice Operator:


--------------------------
x=[10,20,30,40]
y=x[:]
y[1]=777
print(x)->[10,20,30,40]
print(y)->[10,777,30,40]

2)By using copy() Function:


---------------------------
x=[10,20,30,40]
y=x.copy()
y[1]=777
print(x)->[10,20,30,40]
print(y)->[10,777,30,40]

Q) Difference between = Operator and copy() Function


-----------------------------------------------------
= Operator meant for aliasing
copy() Function meant for cloning

Using Mathematical Operators for List Objects:


-----------------------------------------------
We can use + and * operators for List objects.

1)Concatenation Operator (+):


-----------------------------
a=[10,20,30]
b=[40,50,60]
c=a+b
print(c)->[10,20,30,40,50,60]

Note:To use + operator compulsory both arguments should be list objects,


otherwise we will get TypeError.

Eg:
c=a+40->Type error: can only concatenate list(not "int") to list
c=a+[40]->valid

2)Repetition Operator(*):
-------------------------
We can use repetition operator * to repeat elements of list specified
number of times.
x=[10,20,30]
y=x*3
print(y)->[10,20,30,10,20,30,10,20,30]

Comparing List Objects:


-----------------------
We can use comparision operators for list objects.

x=["Dog","Cat","Rat"]
y=["Dog","Cat","Rat"]
z=["DOG","CAT","RAT"]
print(x==y)->True
print(x==z)->False
print(x!=z)->True

Note:Whenever we are using comparison operators (==,!=) for List object


then the
following should be considered.
1)The Number of Elements
2)The Order of Elements
3)The Content of Elements(Case Sensitive)
Note:When ever we are using relational Operators(<,<=,>,>=) between List
Object,
only 1st Element comparison will be performed.

x=[50,20,30]
y=[40,50,60,100,200]
print(x>y)->True
print(x>=y)->True
print(x<y)->False
print(x<=y)->False

Eg:
x=["Dog","Cat","Rat"]
y=["Rat","Cat","Dog"]
print(x>y)->False
print(x>=y)->False
print(x<y)->True
print(x<=y)->True

Membership Operators:
---------------------
We can check wheather element is a member of the or not by using
membership operators.

in Operator
not in Operator

n=[10,20,30,40]
print(10 in n)
print(10 not in n)
print(50 in n)
print(50 not in n)

output:
-------
True
False
False
True
clear() Function:
-----------------
We can use clear() function to remove all elements of List.

n=[10,20,30,40]
print(n)
n.clear()
print(n)

output:
c:\>py test.py
[10,20,30,40]
[]

Nested Lists:
-------------
Sometimes we can take one list inside another list.Such type of lists are
called needed lists.

n=[10,20,[30,40]]
print(n)
print(n[0])
print(n[2])
print(n[2][0])
print(n[2][1])

Output:
c:1> py test.py
[10,20,[30,40]]
10
[30,40]
30
40

Note:We can access nested list elements by using index just like
accessing multi dimensional array elements.

Nested List as Matrix:


----------------------
In Python we can repesent matrix by using nested lists.

n=[[10,20,30],[40,50,60],[70,80,90]]
print(n)
print("Elements by Rows wise:")
for r in n:
print(r)
print("Elements by Matrix style:")
for i in range(len(n)):
for j in range(len(n[i])):
print(n[i][j],end='')
print()

output:
c:1>py test.py
[[10,20,30],[40,50,60],[70,80,90]]

Elements by Row wise:


[10,20,30]
[40,50,60]
[70,80,90]

Elements by Matrix style:


10 20 30
40 50 60
70 80 90

List Comprehensions:
---------------------
It is very easy and compact way of creating list objects from any
iterable objects
(Like List,Tuple,Dictionary,Range etc) based on some condition.

Syntax: list=[expression for item in list if condition]

s=[x*x for x in range(1,11)]


print(s)
v=[2**x for x in range(1,6)]
print(v)
m=[x for x in s if x%2==0]
print(m)

c:\1>py test.py
[1,4,9,16,25,36,49,64,81,100]
[2,4,8,16,32]
[4,16,36,64,100]

eg:
words=["Balaiah","Nag","Venkatesh","Chiranjeevi"]
l=[w[0] for w in words]
print(l)

output: ['B','N','V','C']

num1=[10,20,30,40]
num2=[30,40,50,60]
num3=[i for i in num1 if i not in num2]
print(num3) [10,20]

common elements present in num1 and num2


num4=[i for i in num1 if i in num2]
print(num4) [30,40]

Eg:
words="the quick brown fox jumps over the lazy dog".split()
print(words)
l=[[w.upper(),len(w)] for w in words
print(l)

output:
['the','quick','fox','jumps','over','the','lazy','dog']
[['THE',3],['QUICK',5],['BROWN',5],['FOX',3],['JUMPS',5],['OVER',4],['THE
',3],['LAZY',4],['DOG',3]]

EG:
WRITE A PROGRAM TO DISPLAY UNIQUE VOWELS PRESENT IN THE GIVEN WORD?

vowels=['a','e','i','o','u']
word=input("Enter the word to search for vowels:")
found=[]
for letter in word:
if letter in vowels:
if letter not in found:
found.append(letter)
print(found)
print("The number of different vowels present in",word,"is",len(found))

c:1>py test.py

Enter the word to search for vowels:nicecomputereducation


['i', 'e', 'o', 'u', 'a']
The number of different vowels present in nicecomputereducation is 5

List out all Functions of List and write a program to use these
Functions.

TUPLE DATA STRUCTURES:


-----------------------
1)Tuple is exatly same like as list except that it is immutable.i.e
once we creates Tuple object,we cannot perform any changes in that
object.
2)Hence Tuple is Read only version of List.
3)if our data is fixed and never changes then we should go for Tuple.
4)Insertion order is preserved.
5)Duplicates are allowed.
6)Heterogeneous objects are allowed.
7)We can preserve insertion order and we can differentiate duplicate
objects by using
index.Hence index will play very important role in tuple also.
8)Tuple support both +ve and -ve index.+ve index means forward
direction(from left to right)
and -ve index means backward direction (from right to left)
9)We can represent Tuple elements within parenthesis and with comma
seperator.
10)Parenthesis are optional but recommended to use.

t=10,20,30,40
print(t)
print(type(t))

output:
(10,20,30,40)
<class 'tuple'>
t=()
print(type(t))->tuple

Note:We have to take special care about single valued tuple.compulsary


the value should ends with comma,
otherwise it is treated as tuple.

eg:1
t=(10)
print(t)
print(type(t))

outut
10
<class'int'>
eg:2
t=(10,)
print(t)
print(type(t))

output:
(10,)
<class 'tuple'>

Q) Which of the fallowing are valid Tuple?


t=()
t=10,20,30,40
t=10
t=10,
t=(10)
t=(10,)
t=(10,20,30,40)

Tuple Creation:
---------------
1)t=()
Creation of empty Tuple

2)t=(10,)
t=10,
Creation of Single valued Tuple,Parenthisis are optional,should ends with
comma

3)
t=10,20,30
t=(10,20,30)
Creation of multi values Tuples & Parenthesis are Optional.

4)By using Tuple Functions:

list=[10,20,30]
t=tuple(list)
print(t)
t=tuple(range(10,20,2))
print(t)

Accessing Elements of Tuple:


----------------------------
We can access by index or by slice Operator

1)By using index:


-----------------
t=(10,20,30,40,50,60)
print(t[0])->10
print(t[-1])->60
print(t[100])->index Error:tuple index out of range.

2)By using slice Operator:


--------------------------
t=(10,20,30,40,50,60)
print(t[2:5])
print(t[2:100])
print(t[::2])
output:
(30,40,50)
(30,40,50,60)
(10,30,50)

Tuple vs Immutability:
----------------------
Once we creates Tuple, we cannot change its content.
Hence tuple objects are immutable.

Eg:
t=(10,20,30,40)
t[1]=70->Type Error:'tuple' object does not support item assignment

Mathematical Operators for Tuple:


---------------------------------
We can apply + and * operators for tuple

1)Concatenation Operator (+):


-----------------------------
t1=(10.20,30)
t2=(40,50,60)
t3=t1+t2
print(t3)->(10,20,30,40,50,60)

2)Multiplication Operator OR Repetition Operator(*)

t1=(10,20,30)
t2=t1*3
print(t2)->(10,20,30,10,20,30,10,20,30)

Important Functions of Tuple:


-----------------------------
1))len()
To return number of elements present in the Tuple.

Eg:t=(10,20,30,40)
print(len(t))->4

2)count()
To return number of occurrences of given element in the tuple

Eg:t=(10,20,10,10,20)
print(t.count(10))->3

3)index()
Returns index of first occurences of the given element.
If the specified element is not available then we will get
ValueError.
Eg: t=(10,20,10,10,20)
print(t.index(10))->10
print(t.index(30))->ValueError:tuple.index(x):x not in tuple

4)sorted()
To sort elements based on default natural sorting order.

t=(40,10,30,20)
t1=sorted(t)
print(t1)
print(t)

output:
-------
(10,20,30,40)
(40,10,30,20)

We can sort according to reverse of default Natural sorting order as


fallows
t1=sorted(t,reverse=True)
print(t1)->[40,30,20,10]

5)min() And max() Functions:


-----------------------------
These functions return min and max values according to defualt natural
sorting order.

t=(40,10,30,20)
print(min(t))->10
print(min(t))->40

6)cmp():
--------
It compares the elements of both tuples.
if both tuples are equal then return 0.
if the first tuple is less than second tuple then it returns -1
if the first tuple is greater than second tuple then it returns +1.

t1=(10,20,30)
t2=(40,50,60)
t3=(10,20,30)
print(cmp(t1,t2))->-1
print(cmp(t1,t3))->0
print(cmp(t2,t3))->+1

Note: cmp() function is available only in python2 but not in python3

Tuple packing and Unpacking:


----------------------------

Eg:
a=10
b=20
c=30
d=40
t=a,b,c,d
print(t)->(10,20,30,40)

Here a,b,c,d are packed into a Tuple t.This is nothing but Tuple packing.
Tuple unpacking is the reverse process of Tuple packing.
We can unpack a Tuple and assign its values to different variables.

t=(10,20,30,40)
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)
Output:a=10 b=20 c=30 d=40

Note:At the time of tuple unpacking the number of variables and number of
values
should be same,otherwise we will get ValueError.

Eg:
t=(10,20,30,40)
a,b,c=t->Value Error:too many values to unpack(expected 30)

Tuple Comprehension:
--------------------
Tuple Comprehension is not supported by Python.
t=(x**2 for x in range(1,6))
Here we are not getting tuple object and we are getting generator object.

t=(x**2 for x in range(1,6))


print(type(t))
for x in t:
print(x)

c:1>py test.py
<class 'generator'>
1
4
9
16
25

Q)Write a program to take a Tuple of Numbers from the keyboard and Print
its Sum and Average?

t=eval(input("Enter Tuple of Number:"))


l=len(t)
sum=0
for x in t:
sum=sum+x
print("The sum=",sum)
print("The Average=",sum/l)

c:\1>py test.java
Enter Tuple of Numbers:(10,20,30,40)
The Sum=100
The Average=25.0

c:1>py test.py
Enter Tuple of Numbers:(100,200,300)
The Sum=600
The Average=200.0

Difference between List and Tuple:


-----------------------------------
List and Tuples are exactly same except small difference:List Objects are
mutable where
as Tuple objects are immutable.
In both cases insertion order is presrved, duplicate objects are
allowed,heterogenous
objects are allowed, index and slicing are supported.
List Tuple
1)List is a Group of comma separeated Tuple is a Group of
comma seperated
values within Square Brackets and Values with in
Parenthisis and
square Brackets are mandatory. Parenthisis are optional.
Eg: i=[10,20,30,40] Eg: t=(10,20,30,40)
t=10,20,30,40

2.List Objects are Mutable i.e Once we Tuple Objects are


Immutable i.e once
create List Object we can perform any we create Tuple Object
we cannot
changes in that object. change its content.
Eg:i[1]=70 t[1]=70->ValueError:tuple
object
does not support item assignment.

3)If the Content is not fixed and keep on If the content is


fixed and never changes
changes then we should go for List. then we should go for
Tuple.

4)List Objects can not used as Keys for Tuple Objects can be
used as Keys for
Dictionary because Keys should be Dictionary because
Keys should be
Hashable and Immutable. Hashable and Immutable.

-------------------------------------------------------------------------
--------------------------------------

SET DATA STRUTURES:


-------------------
1)If we want to represent a group of unique values as a single entity
then we should go for set.
2)duplicates are not allowed.
3)insertion order is not preserved.But we can sort the elements.
4)indexing and slicing not allowed for the set.
5)hetrogeneous elements are allowed.
6)set objects are mutable i.e,once we creates set object we can perform
any changes in that object based on our requirement.
7)we can represent set elemets within curly braces and with comma
seperation.
8)we can apply mathematical operations like union,intersection,difference
etc on set objects.

Creation of Set Objects:


-------------------------
s={10,20,30,40}
print(s)
print(type(s))

Output
------
{40,10,20,30}
<class 'set'>

we can create set objects by using set() function s=set(any sequence)

Eg1:
---
L=[10,20,30,40,10,20,10]
s=set(I)
print(s)#{40,10,20,30}
Eg2:
---
s=set(range(5))
print(s)#{0,1,2,3,4}

Note:
-----
while creating empty set we have to take special care.
compulsory we should use set() function.
s={} ->it is treated as dictionary but not empty set.

s={}
print(s)
print(type(s))

Output
-------
{}
<class,'dict'>

Eg:
---
s=set()
print(s)
print(type(s))

Output
------
set()
<class,'set'>

Important Functions of Set:


----------------------------
1)add(x):
---------
Adds item x to the set.
s={10,20,30}
s.add(40);
print(s) #{40,10,20,30}

2)update(x,y,z):
-----------------
To add multiple items to the set.
Arguments are not individual elements and these are iterable objects like
List,Range etc.
All elements present in the given iterable objects will be added to set.

s={10,20,30}
L=[40,50,60,10]
s.update(L,range(5))
print(s)

Output:
------
{0,1,2,3,4,40,10,50,20,60,30}

What is the difference between add() and update() functions in set?


-------------------------------------------------------------------
1) we can use add() to add individual item to the set, where as we can
use update() function to add multiple items to set .
2) add()function can take only one argument where as update() function
can take any number of arguments but all arguments should be iterable
objects

Which of the following are valid for set s?


-------------------------------------------
s.add(10)
s.add(10,20,30)->TypeError:add()takes exactly one argument(3 given)
s.update(10)->TypeError:'int'object is not iterable
s.update(range(1,10,2),range(0,10,2))

3)copy():
---------
1) returns copy of the set.
2) it is cloned object.
s={10,20,30}
s1=s.copy()
print(s1)

4)pop():
--------
it removes and returns some random element from the set.
s={40,10,30,20}
print(s)
print(s.pop())
print(s)

Output
------
{40,10,20,30}
40
{10,20,30}

5)remove(x):
------------
1) It removes specified element from the set.
2) If the specified element not present in the set then we will get
keyError.
s={40,10,30,20}
s.remove(30)
print{<>(s) 40,10,20}
s.remove(50 keyError:<>)50

6)discard(x):
-------------
1) It removes the specified element from the set.
2) If the specified element not present in the set then we won't get any
error.
s={10,20,30}
s.discard(10)
print{<>(s) 20,30}
s.discard(50)
print(<>(s) 20,30}

Q)what is the difference between remove() and discard() functions in set?


Q)explain differences between pop(),remove() and discard() functions in
set?
7)clear():
----------
To remove all elements from the set.
s={10,20,30}
print(s)
s.clear()
print(s)

Output:
-------
{10,20,30}
set()

Mathematical Operations on the Set:


-----------------------------------
1)union():
----------
x.union(y)->we can use this function to return all elements present in
both sets
x.union(y)OR x|y.
x={10,20,30,40}
y={30,40,50,60}
print(x.union(y))->{10,20,30,40,50,60}
print(x|y)->{10,20,30,40,50,60}

2)intersection():
------------------
x.intersection(y)OR x&y.
Returns common elements present in both x and y.
x={10,20,30,40}
y={30,40,50,60}
print(x.intersection(y))->{40,30}
print(x&y)->{40,30}

3)difference():
---------------
x.difference(y) OR x-y.
returns the elements present in x but not in y.
x={10,20,30,40}
y={30,40,50,60}
print(x.difference(y))->10,20
print(x-y)->{10,20}
print(x-y)->{50,60}

4)symmetric_difference():
-------------------------
x.symmetric_difference(y) Or x^y.
Returns elements present in either x OR y but not in both.
x={10,20,30,40}
y={30,40,50,60}
print(x.symmetric_difference(y))->{10,50,20,60}
print(x^y)->{10,50,20,60}

Membership Operators:(in,not in)


--------------------------------
s=set("durga")
print(s)
print('d' in s)
print('z' in s)
Output:
-------
{'u','g','r','d','a'}
True
False

Set Comprehension:
------------------
set comprehension is possible.

s={x*x for x in range(5)}


print(s)->{0,1,4,9,16}

s={2**x for x in range(2,10,2)}


print(s)->{16,256,64,4}

Set Objects won't support indexing and slicing:


-----------------------------------------------
s={10,20,30,40}
print(s[0])->TypeError:'set'object does not support indexing
print(s[1:3])->TypeError:'set'object is not subscriptable

Write a program to eliminate duplicates present in the list?


------------------------------------------------------------
Approach-1
Approach-2
1) l=eval(input('enter list values:")) 1) l=eval(input('enter
list of values:"))
2) s=set(l) 2) l1=[]
3) print(s) 3) for x in l:
4) if x not in l1:
D:\Python_classes>py test.py 5) l1.append(x)
Enter List of values:[10,20,30,10,20,40] 6) print(l1)
{40,10,20,30}

D:\Python_classes>py test.py
enter list of
values:[10,20,30,10,20,40]
[10,20,30,40]

Q)Write a program to print different vowels present in the given word?


w=input("enter word to search for vowels:")
s=set(w)
v={'a','e','i','o','u'}
d=s.intersection(v)
print("The different vowel present in",w,"are",d)

D:\Python_classes>py test.py
Enter word to search for vowels:durga
The different vowel present in durga are{'u','a'}

DICTIONARY DATA STRUCTURE:


--------------------------
We can use List,Tuple and Set to represent a group of individual object
as a single entity.
If we want to represent a group of objects as key-value pairs then we
should go for Dictionary.
Eg:
rollno----name
phone number---address
ipaddress----domainname

Duplicate keys are not allowed but values can be duplicated.


Hetrogeneous objetcs are allowed for both key and values.
Insertion order is not preserved.
Dictionaries are mutable
Dictionaries are dynamic
indexing and slicing concepts are not applicable.

Note:In c++ and java Dictionaries are known as "Map" where as in Perl and
Ruby It is Known as "Hash"

How to create Dictionary?


-------------------------
d={} or d-dict()
We are creating empty dictionary.We can add entries as fallows.
d[100]="durga"
d[200]="ravi"
d[300]="shiva"
print(d)->{100:'durga',200:'ravi',300:'shiva'}

If we know data in advance then we can create disctionary as follows

d={100:'durga',200:'ravi',300:'shiva'}
d={key:value,key:value}

How to Access Data from the dictionary?


-----------------------------------------
We can access the data bu using keys.

d={100:'durga',200:'ravi',300:'shiva'}
print(d[100]) #durga
print(d[300]) #shiva

If the specified key is not available then we will get keyError


print(d[400])->key error

we can represent this by checking whether is already available or not by


using has_key() function or by using in oprator.
d.has_key(400)-> Returns 1 if key is available otherwise returns 0
But has_key()function is available only in python 2 but not in python 3.
Hence compulsory we have to use in operator.
if 400 in d:
print(d[400])

q)write a program to enter name and percantage marks in a Dictionary and


display information on the screen
-------------------------------------------------------------------------
-----------------------------------
rec={}
n=int(input("Enter number of students:"))
i=1
while i<=n:
name =input("Enter student name:")
marks=input("Enter % of marks of student:")
rec[name]=marks
i=i+1
print("Name of student",name,"% of marks",marks)
for x in rec:
print("\t",x,"\t",rec[x])

D:\python_classes>py test.py
Enter number of students:3
Enter student name :durga
Enter % of marks of student:60%
Enter student name : ravi
Enter % of marks of student:70%
Enter student name : shiva
Enter % of marks of student :80%
Name of student % of marks
--------------- -----------
Durga 60%
ravi 70%
shiva 80%

How to Update Dictionaries


--------------------------
d[key]=value
if the key is not available then a new entry will be added to the
dictionary with the specified key-value pair
if the key is already available then old value will be replaced with new
value.
d={100:"durga",200:"ravi",300:"shiva"}
print(d)
d[400]="pavan"
print(d)
d[100]="suanny"
print(d)
output
{100:'durga',200:'ravi',300:'shiva'}
{100:'durga',200:'ravi',300:'shiva',400:'pavan'}
{100:'sunny',200:'ravi',300:'shiva',400:'pavan'}

How to delete elements fron dictionary?


1)del d[key]
------------
it deletes entry associated with the specified key.
if the key is not available then we will get keyerror.
d={100:"durga",200:"ravi",300:"shiva"}
print(d)
del d[100]
print(d)
del d[400]
output
{100:'durga',200:'ravi',300:'shiva'}
{200:'ravi',300:'shiva'}
keyerror:400

2)d.clear()
---------
To remove all entries from the dictionary.
d={100:"durga",200:"ravi",300:"shiva"}
print(d)
d.clear()
print(d)

output:
{100:'durga',200:'ravi',300:'shiva'}
{}

3)del d:
-------
to delete total dictionary. Now we cannot access d.
d= {100:"durga",200:'ravi',300:"shiva"}
print(d)
del d
print(d)
output:
-------
{100:'durga',200:'ravi',300:'shiva'}
nameerror: name 'd' is not defined

Important functions of dictionary:


----------------------------------
1)dict():
to create a dictionary

d=dict()-> it creates dictionary


d=dict({100:"durga",200:"ravi"})-> it creaters dictionary with specified
elements
d=dict([(100,"durga"),(200,"shiva"),(300,"ravi")])
-> it creates dictionary with the given list of tuple elements
2)len():
returns the number of items in the dictionary.

3)clear():
To remove all elements from the dictionary.

4)get():
To get the value associated with the key
d.get(key)
if the key is available then returns the corresponding value otherwise
returns None.it wont raise any error.
d.get (key,defaultvalue)
if the key is availble then returns the corresponding value otherwise
returns default value.
d={100:"durga",200:"ravi",300:"shiva"}
print(d[100])-> durga
print(d[100])->keyerror:400
print(d.get(100))->durga
print(d.get(400))->none
print(d.get(100,'Guest'))->durga
print(d.get(400,'Guest'))->Guest

5)pop():
--------
d.pop(key)
1).It removes the entry associated with the specified key and return the
corresponding value.
2).If the specified key is not available then we will get KeyError.

d={100:"durga",200:"ravi",300:"shiva"}
print(d.pop(100))
print(d)
print(d.pop(400))

output
------
durga
{200:'ravi',300:'shiva'}
KeyError:400

6)popitem():
-------------
It removes an arbitrary item(key-value)from the dictionary and returns
it.

d={100:"durga",200:"ravi",300:"shiva"}
print(d)
print(d.popitem())
print(d)

output
------
{100:'durga',200:'ravi',300:'shiva'}
(300,'shiva')
{100:'durga',200:'ravi'}
if the dictionary is empty then we will get KeyError
d={}
print(d.popitem())==>KeyError:'popitem():dictionary is empty'

7)keys():
----------
it returns all keys associated eith dictionary.

d={100:"durga",200:"ravi",300:"shiva"}
print(d.keys())
for k in d.keys():
print(k)

output
------
dict_keys([100,200,300])
100
200
300

8)values():
-----------
It returns all values associated with the dictionary.

d={100:"durga",200:"ravi",300:"shiva"}
print(d.values())
for v in d.values
print(v)

output
------
dict_values(['durga','ravi','shiva'])
durga
ravi
shiva

9)items():
----------
It returns list of tuples representing key-value pairs.
[(k,v),(k,v),(k,v)]
d={100:"durga",200:"ravi",300:"shiva"}
for k,v in d.items():
print(k,"--",v)

output
-------
100--durga
200--ravi
300--shiva

10)copy():
-----------
To create exactly duplicate dictionary(cloned copy)
d1=d.copy();

11)setdefault():
----------------
d.setdefault(k,v)
1)If the key is already available then this function returns the
corresponding value.
2)If the key is not available then the specified key-value will be added
as new item to the dictionary.

d={100:"durga",200:"ravi",300:"shiva"}
print(d.setdefault(400,"pavan"))
print(d)
print(d.setdefault(100,"sachin"))
print(d)

output
-------
pavan
{100:'durga',200:'ravi',300:'shiva',400:'pavan'}
durga
{100.'durga',200:'ravi',300:'shiva',400:'pavan'}

12)update():
-------------
d.update(x)
All items present in the dictionary x will be added to dictionary d

Q) write a program to take dictionary from the keyboard and print the sum
of values?
-------------------------------------------------------------------------
------------
d=eval(input("Enter dictionary:"))
s=sum(d.values())
print("sum=",s)

output
------
D:\python_classws>py test.py
Enter dictionary:{'A':100,'B':200,'c':300}
sum=600

Q)write a program to find number of occurences of each letter present in


the given string?
-------------------------------------------------------------------------
------------------
word=input("enter any word:")
d={}
for x in word:
d[x]=d.get(x,0)+1
for k,v in d.items():
print(k,"occurred",v,"times")

output
------
D:\python_classws>py test.py
Enter any word:mississippi
m occurred 1 times
i occurred 4 times
s occurred 4 times
p occurred 2 times

Q)write a program to find number of occurrences of each vowel present in


the given string?
-------------------------------------------------------------------------
------------------
word=input("Enter any word:")
vowels={'a','e','i','o','u'}
d={}
for x in word:
if x in vowels:
d[x]=d.get(x,0)+1
for k,v in sorted(d.items()):
print(k,"occurred",v,"times")

output
-------
D:\python_classws>py test.py
Enter any word:doganimaldoganimal
a occurred 4 times
i occurred 2 times
o occurred 2 times

Q)write a program to accept student name and marks from the keyboard and
creates a dictionary.also display student marks by taking
-------------------------------------------------------------------------
-----------------------------------------------------------
student name as input?
-----------------------

n=int(input("Enter the number of students:")


d={}
for i in range(n):
name=input("Enter student Name:")
marks=input("Enter student Marks:")
d[name]=marks
while True:
name=input("Enter student Name to get marks:")
marks=d.get(name,-1)
if marks==-1;
print("student not found")
else;
print("the marks of",name,"are",marks)
option=input("Do you want to find another student marks[Yes|No])
if option=="No":
break
print("Thanks for using our application")

output
------

D:\python_classws>py test.py
Enter the number of students:5

Enter Student Name:sunny


Enter Student Marks:90

Enter Student Name:banny


Enter Student Marks:80

Enter Student Name:chinny


Enter Student Marks:70

Enter Student Name:pinny


Enter Student Marks:60

Enter Student Name:


vinny
Enter Student Marks:50

Enter Student Name to get Marks:sunny


The Marks of sunny are 90

Do you want to find another student marks[Yes|no]Yes

Enter Student Name to get Marks:durga


Student not found

Do you want to find another student marks[Yes|no]No


Thanks for using our application

Dictionary Comprehension:
--------------------------
Comprehension concept application for dictionaries also.

squares={x:x*x for x in range(1,6)}


print(squares)
doubles={x:2*x for x in range(1,6)}
print(doubles)

output
-------
{1:1,2:4,3:9,4:16,5:25}
{1:1,2:4,3:6,4:8,5:10}

-------------------------------------------------------------------------
---------------------------------

FUNCTIONS
----------
-If a group of statements is repeatedly required then it is not
recommended to write these statements everytime seperately.we have to
define these statements as a single unit and we can call that unit any
number of times based on our requirement without rewriting.This unit is
nothing but function
-The main advantage of functions is code reusability.

Note:In other language functions are known as


methods,procedures,subroutines etc

Python supports 2 types of functions


1)Built in functions
2)User Defined Functions

1)Built in functions
----------------------
The functions which are coming along with python software
automatically,are called built in functions or pre defined functions.

Eg:
----
id()
type()
input()
eval()
etc..

2)User Defined Functions:


--------------------------
The functions which are developed by programmer explicitly according to
business requiremets, are called user defined functions.

Syntax to create User defined Functions:


----------------------------------------
def function_name(parameters):
"""doc string"""
---
----
return value

note:
-----
while creating functions we can use 2 keywords
1)def(mandatory)
2)return(optional)

Eg 1:
-----
write a function to print hello

test.py
-------
1)def wish():
2) print("hello Good Morning")
3) wish()
4) wish()
5) wish()

Parameters
-----------
parameters are inputs to the function.if a function contains
parameters,then at the time of calling,compulsory we should provide
values otherwise,otherwise we will get error.
Eg:
---
write a function to take name of the student as input and print wish
message by name.
1) def wish(name):
2) print("hello",name,"Good Morning")
3) wish("durga")
4) wish("Ravi")

D:/Python_classses>py test.py
Hello Durga Good morning
Hello Ravi Good Morning

Eg:write a function to take number as input and print its square value
--

1) def squarelt(number):
2) print("The Square of",number,"is",number*number)
3) squarelt(4)
4) squarelt(5)

D:/Python_classses>py test.py
The Square of 4 is 16
The Square of 5 is 25

Return Statement:
-----------------
Function can take input values as parameters and executes business
logic,and returns output to the caller with return statement.

Q)write a function to accept 2 numbers as input and return sum


----------------------------------------------------------------
1)def add(x,y):
2) return x+y
3) result=add(10,20)
4) print("The sum is",result)
5) print("The sum is",add(100,200))

D:/Python_classses>py test.py
The sum is 30
The sum is 300

If we are not writing return statement then default return value is None.
1) def f1():
2) print("Hello")
3) f1()
4) print(f1())

output
-------
Hello
Hello
None

Q) write a function to check whether the given number is even or odd?


----------------------------------------------------------------------

1)def even_odd(num):
2) if num%2==0:
3) print(num,"is Even Number")
4) else:
5) print(num,"is odd number")
6) even_odd(10)
7) even_odd(15)

output
-------
D:/Python_classses>py test.py
10 is even number
15 is odd number

Q) write a function to find factorial of given number?


-------------------------------------------------------
1) def fact(num):
2) result=1
3) while num>=1:
4) result=result*num
5) num=num-1
6) return result
7) for i in range(1,5):
8) print("The Factorial of",i,"is:",fact(i))

Output
-------
D:/Python_classses>py test.py
The Factorial of 1 is : 1
The Factorial of 2 is : 2
The Factorial of 3 is : 6
The Factorial of 4 is : 24

Returning Multiple Values from a Function:


-------------------------------------------
In other languages like c,c++ and java,function can return atmost one
value.But in Python,a function can return any number of values.

Eg 1:
------
1) def sum_sub(a,b):
2) sum=a+b
3) sub=a-b
4) return sum,sub
5) x,y=sum_sub(100,50)
6) print("The sum is :",x)
7) print("The substraction is:",y)

Output
------
The sum is: 150
The substraction is :50

Eg 2:
-----
1) def calc(a,b):
2) sum=a+b
3) sub=a-b
4) mul=a*b
5) div=a/b
6) return sum,sub,mul,div
7) t=calc(100,50)
8) print("The Results are")
9) for i in t:
10) print(i)

Output:
-------
The Results are
150
50
5000
2.0

Types of arguments
-------------------
def f1(a,b)
------
------
------
f1(10,20)

a,b are formal arguments where as 10,20 are acutal arguments.

There are 4 types are actual arguments are allowed in python.


1) Positional Arguments
2) Keyword Arguments
3) Default Arguments
4) variable Length Arguments

1) Positional Arguments
-----------------------
-> These are the arguments passed to function in correct positional
order.
def sub(a,b)
print(a-b)

sub(100,200)
sub(200,100)
-> The number of arguments and postion of arguments must be matched.if we
change the order then result may be changed.
-> If we change the number of arguments then we will get error.

2)Keyword Arguments:
--------------------
we can pass argument values by keyword i.e, by parameter name.

1) def wish(name,msg):
2) print("hello",name,mgs)
3) wish(name="Durga",mgs="Good Morning")
4) wish(mgs="Good Morning",name="Durga")

Output
------
Hello Durga Good Morning
Hello Durga Good Morning
Here the order of arguments is not important but number of arguments must
be matched.

Note:
----
We can use both positional and keyword arguments simultaneously.But first
we have to take positional arguments and then keyword arguments,otherwise
we will get syntax error.

1) def wish(name,msg):
2) print("Hello",name,mgs)
3) wish("Durga","GoodMorning")->valid
4) wish("Durga",msg="GoodMorning")->valid
5) wish(name="Durga","GoodMorning")->invalid
6) SyntaxError:positional argument follows keyword argument

3)Default Arguments:
---------------------
sometimes we can provide default values for our positional arguments.

1) def wish(name="Guest"):
2) print("Hello",name,"Good Morning")
3) wish("Durga")
4) wish()

Output
-------
Hello Durga Good Morning
Hello Guest Good Morning
If we are not passing any name then only default value will be considered

***Note:
--------
After default arguments we should not take non default arguments.

1) def wish(name="Guest",msg="Good Morning"):->valid


2) def wish(name,msg="Good Morning"):->valid
3) def wish(name="Guest",msg):->Invalid

SyntaxError:non-default argument follows default argument

4)variable Length Arguments:


----------------------------

-sometimes we can pass variable number of arguments to our function,such


type of arguments are called variable length arguments.
-We can declare a variable length argument with *symbol as follows
-def f1(*n):
-we can call this function by passing any number of arguments including
zero number.
-Internally all these values represented in the form of tuple.

1) def sum(*n):
2) total=0
3) for n1 in n:
4) total=total+n1
5) print("The Sum=",total)
6)
7) sum()
8) sum(10)
9) sum(10,20)
10) sum(10,20,30,40)

Output
-------
The sum=0
The sum=10
The sum=30
The sum=100

Note:
-----
we can mix variable length arguments with positional arguments.

1) def f1(n1,*s):
2) print(n1)
3) for s1 in s:
4) print(s1)
5)
6) f1(10)
7) f1(10,20,30,40)
8) f1(10,"A",30,"B")

Output
-------
10
10
20
30
40
10
A
30
B

Note:
----
After variable length argument,if we are taking any other arguments then
we should provide values as keyword arguments.
1) def f1(*s,n1):
2) for s1 in s:
3) print(s1)
4) print(n1)
5)
6) f1("A","B",n1=10)

Output
------
A
B
10
f1("A","B",10)->Invalid
TypeError:f1()missing 1 required keyword-only argument:'n1'

Note:
----
We can declare key word variable length arguments also.

*For thia we have to use**.


*def f1(**n):
*we can call this function by passing any number of keyword
arguments.internally these keyword arguments will be stored inside a
dictionary
1) def display(**kwargs):
2) for k,v in kwargs.items():
3) print(k,"=",v)
4) display(n1=10,n2=20,n3=30)
5) display(rno=100,name="Durga",marks=70,subject="Java")

Output
------
n1 = 10
n2 = 20
n3 = 30
rno = 100
name = Durga
marks = 70
subject = Java

Case Study:
-----------

def f(arg1,arg2,arg3=4,arg4=8):
print(arg1,arg2,arg3,arg4)
1) f(3,2)-> 3 2 4 8

2) f(10,20,30,40)-> 10,20,30,40

3) f(25,50,arg4=100)->25 50 4 100

4) f(arg4=2,arg1=3,arg2=4) -> 3 4 4 2

5) f()-> Invalid
TypeError: f() missing 2 required positional arguments:'arg1' and
'arg2'

6) f(arg3=10,arg4=20,30,40)-> Invalid
SyntaxError: positional argument follows keyword argument
[After Keyword arguments we should not take positional arguments]

7) f(4,5,arg2=6)->Invalid
TypeError:f()got an multiple values for argument 'arg2'

8) f(4,5 arg3=5,arg5=6)->Invalid
TypeError:f() got an unexpected keyword argument 'arg5'

Note:
-----
Function vs module vs Library
1) A group of lines with some name is called a function
2) A group of functions saved to a file, is called module
3) A group of modules is nothing but library

Library
------------------------------
module1 module2
-------- --------
function 1 function 1
function 2 function 2
function 3 function 3
function

---------
---------
---------
---------
---------
---------
---------
---------

Types of Variables
-------------------
python supports 2 types of variables.
1) Global Variables
2) local Variables

1) Global Variables
--------------------
- The variables which are declared outside of function are called global
variables.
- These variables can be accessed in all functions of that module.

1) a=10 #global variable


2) def f1():
3) print(a)
4)
5) def f2():
6) print(a)
7)
8) f1()
9) f2()

Output
------
10
10

2)Local Variables:
------------------
* The variables which are declared inside a function are called local
variables.
* Local variables are available only for the function in which we
declared it.i.e from outside of function we cannot access.

1) def f1():
2) a=10
3) print(a) #valid
4)
5) def f2():
6) print(a) #invalid
7)
8) f1()
9) f2()

NameError: name'a' is not defined

Global keyword:
---------------
we can use global keyword for the following 2 purposes:
1) To declare global variable inside function
2) To make global variable available to the function so that we can
perfom required modifications

1) a=10
2) def f1():
3) a=777
4) print(a)
5)
6) def f2():
7) print(a)
8)
9) f1()
10) f2()
11)

Output
-------
777
10

1) a=10
2) def f1():
3) global a
4) a=777
5) print(a)
6) def f2():
7) print(a)
8)
9) f1()
10) f2()

Output
------
777
777

1) def f1():
2) a=10
3) print(a)
4)
5) def f2():
6) print(a)
7)
8) f1()
9) f2()

Output:
-------
NameError:name'a' is not defined
1) def f1():
2) global a
3) a=10
4) print(a)
5)
6) def f2():
7) print(a)
8)
9) f1()
10) f2()

Output:
-------
10
10

Note:
----
If global variable and local variable having the same name then we can
access global variable inside a function as follows

1) a=10->Global variable
2) def f1():
3) a=777->Local Variable
4) print(a)
5) print(gllobals()['a'])
6) f1()

Output
-------
777
10

Recursive functions
-------------------
A function that calls itself is known as Recursive Function.

Eg:
---
factorial(3)= 3*factorial(2)
= 3*2*factorial(1)
= 3*2*1*factorial(0)
= 3*2*1*1
= 6
factorial(n)= n*factorial(n-1)

The main advantage of recursive functions are:


1) we can reduce length of the code and improves readability.
2) we can solve complex problems very easily.

Q) Write a Python Function to find factorial of given Number with


Recursion
-------------------------------------------------------------------------
---

1) def factorial(n):
2) if n==0:
3) result=1
4) else:
5) result=n*factorial(n-1)
6) return result
7) print("Factorial of 4 is:",factorial(4))
8) print("Factorial of 5 is:",factorial(5))

Output
------
Factorial of 4 is: 24
Factorial of 5 is : 120
Anonymous Functions:
--------------------
-Sometimes we can declare a function without any name,such type of
nameless functions are called anonymous functions or lambda functions.
-The main purpose of anonymous function is just for instant use(i,e for
one time usage)

Normal Function:
----------------
We can define by using def keyword.
def squarelt(n):
return n*n

Lambda Function:
----------------
we can define by using lambda keyword lambda n:n*n

Syntax of lambda Function:


--------------------------
lambda argument_list:expression

Note:
-----
By using lambda Functions we can write very concise code so that
readability of the program will be improved.

Q)Write a Program to create a lambda function to find Square of given


number?
-------------------------------------------------------------------------
------
1) s=lambda n:n*n
2) print("The Square of 4 is:",s(4))
3) print("The Square of 5 is:",s(5))

Output
-------
The square of 4 is:16
The square of 5 is:25

Q) Lambda Function to find Sum of 2 given Numbers


-------------------------------------------------
1) s= lambda a,b:a+b
2) print("The Sum of 10,20 is:",s(10,20))
3) print("The Sum of 100,200 is:",s(100,200))

Output
-----
The Sum of 10,20 is: 30
The Sum of 100,200 is: 300

Q) Lambda Function to find biggest of given Values


--------------------------------------------------
1) s=lambda a,b:a if a>b else b
2) print("The Biggest of 10,20 is:",s(10,20))
3) print("The Bigggest of 100,200 is:",s(100,200))

Output
------
The Biggest of 10,20 is:20
The Biggest of 100,200 is:200

Note:
-----
Lambda Function internally returns expression value and we are not
required to write return statement explicitly.

Note:
-----
Sometimes we can pass function as argument to another function.In such
cases lambda functions are best choice.

We can use lambda functions very commonly with filter(),map() and


reduce() functions, because these functions expect function as argument.

Filter() Function:
------------------
We can use filter() function to filter values from the given sequence
based on some comdition.

filter(function,sequence)

Where Function Argument is responsible to perform conditional check


sequence can be List OR Tuple OR String.

Q) Program to filter only Even Numbers from the List by using filter()
Function?
-------------------------------------------------------------------------
--------

Without Lambda Function:


-----------------------
1) def is Even(x):
2) if x%2==0:
3) return True
4) else:
5) return False
6) l=[0,5,10,15,20,25,30]
7) l1=list(filter(isEven,l))
8) print(l1) #[0,10,20,30]

With Lambda Function:


---------------------
1) l=[0,5,10,15,20,25,30]
2) l1=list(filter(lambda x:x%2==0,l))
3) print(l1) #[0,10,20,30]
4) l2=list(filter(lambda x:x%2!=0,l))
5) print(l2) #[5,15,25]

map()Function:
--------------
-> For every element present in the given sequence,apply some
functionality and generate new element with the required
modification.For this requirement we should go for map() function.

-> Eg:For every element present in the list perform double and generate
new list of doubles.
Syntax:
-------
map(function,sequence)

-> The function can be applied on each element of sequence and generates
new sequence.

Without Lambda
--------------
1) l=[1,2,3,4,5]
2) def doublelt(x):
3) return 2*x
4) l1=list(map(doublelt,l))
5) print(l1) #[2,4,6,8,10]

With Lambda
------------
1) l=[1,2,3,4,5]
2) l1=list(map(lambda x:2*x,l))
3) print(l1) #[2,4,6,8,10]

Eg 2:
-----
To find square of given numbers

1) l=[1,2,3,4,5]
2) l1==list(map(lambda x:x*x,l))
3) print(l1) #[1,4,9,16,25]

We can apply map() function on multiple lists also.But make sure all list
should have same length.

Syntax:
-------
map(lambda x,y:x*y,l1,l2))
x is from l1 and y is from l2

1) l1=[1,2,3,4]
2) l2=[2,3,4,5]
3) l3=list(map(lambda x,y:x*y,l1,l2))
4) print(l3) #[2,6,12,20]

reduce()Function:
-----------------
- reduce()function reduces sequences of elements into a single element by
applying the specified function.
- reduce(function,sequence)
- reduce() function present in functools module and hence we should write
import statement.

1) from functools import*


2) l=[10,20,30,40,50]
3) result=reduce(lambda x,y:x+y,l)
4) print(result) #150

Eg:
---
1) result=reduce(lambda x,y:x*y,l)
2) print(result) #12000000

Eg:
---
1) from functools import*
2) result=reduce(lambda x,y:x+y,range(1,101))
3) print(result) #5050

Everything is an Object:
------------------------
- In Python every thing is treated as object.
- Even functions also internally treated as objects only.

1) def f1():
2) print("Hello")
3) print(f1)
4) print(id(f1))

Output:
-------
<function f1 at 0x00419618>
4298264

Function Aliasing:
------------------
For the existing function we can give another name,which is nothing but
function aliasing.

1) def wish(name):
2) print("Good Morning:",name)
3)
4) greeting=wish
5) print(id(wish))
6) print(id(greeting))
7)
8) greeting('Durga')
9) wish('Durga')

Output:
------
4429336
4429336
Good Morning:Durga
Good Morning:Durga

Note:
----
- In the above example only one functional is available but we can call
that function by using either wish name or greeting name.
- If we delete one name still we can access that function by using alias
name.

1) def wish(name):
2) print("Good Morning:",name)
3)
4) greeting=wish
5)
6) greeting('Durga')
7) wish('Durga')
8)
9) del wish
10) #wish('Durga')->NameError: name'wish'is not defined
11) greeting('pavan')

Output:
-------
Good Morning:Durga
Good Morning:Durga
Good Morning:pavan

Nested Functions:
-----------------
We can declare a function inside another function,such type of functions
are called Nested functions.

def f1():
def inner(a,b):
print("The sum=",a+b)
print("The Average=",(a+b)/2)
print()
inner(10,20)
inner(20,30)
inner(40,50)
inner(100,200)
f1()

eg:2
-----

1) def outer():
2) print("outer function started")
3) def inner():
4) print("inner function execution")
5) print("outer function calling inner function")
6) inner()
7) outer()
8) #inner()->NameError:name'inner' is not defined

Output:
-------
outer function started
outer function calling inner function
inner function execution

In the above example inner() function is local to outer() function and


hence it is not possible to call directly from outside of
outer()function.

Note:
-----
A function can return another function.

1) def outer():
2) print("outer function started")
3) def inner():
4) print("inner function execution")
5) print("outer function returning inner function")
6) return inner
7) f1=outer()
8) f1()
9) f1()
10) f1()

Output:
-------
outer function started
outer function returning inner function
inner function execution
inner function execution
inner function execution

Q)What is the difference between the following lines?


------------------------------------------------------

f1=outer
f1=outer()

- In the first case for the outer() function we are providing another
name f1 (function aliasing).
- But in the second case we calling outer() function,which returns inner
function.For that inner function() we are providing another name f1

Note:
----
We can pass function as argument to another function

Eg:
---
filter(function,sequence)
map(function,sequence)
reduce(function,sequence)

Decorators:
------------
def decor(func):
def inner(name):
if name=='sunny':
print("Hello sunny bad moring..")
else:
func(name)
return inner

@decor
def wish(name):
print("Hello",name,"Good Morning")

wish("Naresh")
wish("Ravi")
wish("Sunny")

eg:2
def decor(func):
def inner(name):
if name=='sunny':
print("Hello sunny bad moring..")
else:
func(name)
return inner
def wish(name):
print("Hello",name,"Good Morning")
decorfunction=decor(wish)
wish("Sunny")
decorfunction("Sunny")

wish("NARESH")
decorfunction("NARESH")

EG:3
def smartdivision(func):
def inner(a,b):
if b==0:
print("Hello stupid..How can divide with zero")

else:
return func(a,b)
return inner

@smartdivision
def division(a,b):
retun a/b

print(division(10,2))
print(division(10,5))
print(division(10,0))

-------------------------------------------------------------------------
------------------------------------------------------------

MODULES
-------
- A group of functions, variables and classes saved to a file, which is
nothing but module.
- Every python file(.py) acts as a module.

nareshmath.py
-------------

1) x=888
2)
3) def add(a,b):
4) print("The Sum:",a+b)
5)
6) def product(a,b):
7) print("The product:",a*b)

- durgamath module contains one variable and 2 functions.


- If we want to use members of module in our program then we should
import that module.
import modulename
- We can access members by using module name.
modulename.variable
modulename.function()

test.py:
--------
1) import durgamath
2) print(durgamath.x)
3) durgamath.add(10,20)
4) durgamath.product(.10,20)

Output
------
888
The Sum: 30
The Product:200

Note:
----
Whenever we are using a module in our program,for that module compiled
file will be generated and stored in the hard disk permanently.

Renaming a module at the time of import


----------------------------------------
(Module Aliasing):
------------------
- Eg: import durgamath as m
- Here durgamath is original module name and m is alias name.
- We can access members by using alias name m

test.py:
-------
1) import durgamath as m
2) print(m.x)
3) m.add(10,20)
4) m.product(10,20)

from...import:
--------------
We can import particular members of module by using from...import.
The main advantage of this is we can access members directly without
using module name.

1) from durgamath import x,add


2) print(x)
3) add(10,20)
4) product(10,20)-> NameError:name'product'is not defined

We can import all members of a module as follows from durgamath import*

test.py:
--------
1) from durgamath import*
2) print(x)
3) add(10,20)
4) product(10,20)

Various Possibilities of import:


--------------------------------
1) import modulename
2) import module1,module2,module3
3) import module1 as m
4) import module1 as m1,module2 as m2,module3
5) import module import member
6) from module import member1,member2,member3
7) from module import member1 as x
8) from module import*

Member Aliasing:
----------------
1) from durgamath import x as y, add as sum
2) print(y)
3) sum(10,20)

Once we defined as alias name,we should use alias name only and we should
not use original name

1) from durgamath import x as y


2) print(x)-> NameError:name'x' is not defined

Reloading a Module:
-------------------
By default module will be loaded only once eventhough we are importing
multiple times.

module1.py:
----------
print("This is from module1")

test.py
--------
1) import module1
2) import module1
3) import module1
4) import module1
5) print("This is test module")

Output
------
This is from module1
This is test module

- In the above program test module will be loaded only once eventhough we
are importing multiple times.

- The problem in this approach is after loading a module if it is updated


outside then updated version of module1 is not available to our
program.

- We can solve this problem by reloading module explicitly based on our


requirement.
- We can reload by using reload() function of imp module.

1) import imp
2) imp.reload(module1)

test.py:
--------
1) import module1
2) import module1
3) from imp import reload
4) reload(module1)
5) reload(module1)
6) reload(module1)
7) print("This is test module")
In the above program module1 will be loaded 4 times in that 1 time by
default and 3 times explicity. In this case output is

1) This is from module1


2) This is from module1
3) This is from module1
4) This is from module1
5) This is test module

The main advantage of explicit module reloading is we can ensure that


updated version is always available to our program.

Another example:

module1.py:
----------
1.print("This is from module1")

test.py:
-------
import time
from imp import reload
import module1
print("profram enter into sleeping state")
time.sleep(30)
reload(module1)
print("program entering into again sleeping state")
reload(module1)
print("this is the last line")

Finding Members of Module by using dir()Function:


-------------------------------------------------
Python provides inbuilt function dir() to list out all members of
current module or a specified module.

dir()->To list out all members of current module


dir(moduleName)->To list out all members of specified module

Eg 1:test.py
------------
1) x=10
2) y=20
3) def f1()
4) print("hello")
5) print(dir()) #To print all members of specified module

Eg 1:test.py
------------
1) x=10
2) y=20
3) def f1():
4) print("Hello")
5) print(dir()) #To print all members of current module

Output
------
['_annotations_','_builtins_','_cached_','_doc_','file_','_loader_','_nam
e_','package_','_spec_','f1','x','y']

Eg 2:
----
To display members of particular module

durgamath.py:
--------------
1) x=888
2)
3) def add(a,b)
4) print("The sum:",a+b)
5)
6) def product(a,b):
7) print("The product:",a*b)

test.py:
--------
1) import durgamath
2) print(dir(durgamath))

output
-------
['_builtins_','_cached_','_doc_','_file_','_loader_','_name_','_package_'
,'_spec_','add','product','x']

Note:
-----
For every module at the time of execution python interpreter will add
some special properties automatically for internal use.

Eg:
---
_builtins_,_cached_,_doc_,_file_,_loader_,_name_,_package_,_spec_

Based on our requirement we can access these properties also in our


program.

Eg:
---
test.py

1)print(_builtins_)
2)print(_cached_)
3)print(_doc_)
4)print(_file_)
5)print(_loader_)
6)print(_name_)
7)print(_package_)
8)print(_spec_)

Output
-------
<module'builtins'(built-in)>
None
None

test.py
-------

1)<_frozen_importlib_external.SourceFileLoader object at 0x00572170>


2) _main_
3) None
4) None

The Special Variable_name_:


---------------------------
- For every Python program,a special variable_name_will be added
internally.
- This variable stores information regarding whether the program is
executed as an individual program or as a module.
- If the program executed as an individual program then the value of this
variable is _main_
- If the program executed as a module from some other program then the
value of this variable is the name of module where it is defined.
- Hence by using this_name_variable we can identify whether the program
executed directly or as a module.

Demo program:
-------------

module1.py:
-----------
1) def f1():
2) if_name_=='_main_':
3) print("The code executed as a program")
4) else:
5) print("The code executed as a module from some other program")
6) f1()

test.py:
--------
1) import module1
2) module1.f1()

D:\Python_classes>py module1.py
The code executed as a program

D:\Python_classes>py test.py
The code executed as a module from some other program
The code executed as a module from some other program

Working with math Module:


-------------------------
- Python provides inbuilt module math.
- This module defines several functions which can be used for
mathematical operations.
- The main important functions are
NAGANAGA 1) sqrt(x)
2) ceil(x)
3) floor(x)
4) fabs(x)
5) log(x)
6) sin(x)
7) tan(x)
8) ....

1) from math import*


2) print(sqrt(4))
3) print(ceil(10.1))
4) print(floor(10.1))
5) print(fabs(-10.6))
6) print(fabs(10.6))

Output
-------
2.0
11
10
10.6
10.6

Note:
-----
We can find help for any module by using help() function

Eg:
---
import math
help(math)

Working with random module:


---------------------------
- This module defines several functions to generate random numbers.
- We can use these functions while developing games, in cryptography and
to generate random numbers on fly for authentication.

1) random()Function:
--------------------
This function always generate some float value between o and 1( not
inclusive)
0<x<1
1) from random import*
2) for i in range(10):
3) print(random())

Output
------
0.4572685609302056
0.6584325233197768
0.15444034016553587
0.18351427005232201
0.1330257265904884
0.9291139798071045
0.6586741197891783
0.8901649834019002
0.25540891083913053
0.7290504335962871

2) randint() Function:
---------------------
To generate random integer betweeen two given numbers(inclusive)

1) from random import*


2) for i in range(10):
3) print(randint(1,100)) # generate random int value between 1 and
100(inclusive)
Output
------
51
44
39
70
49
74
52
10
40
8

3)uniform()Function:
---------------------
It returns random float values between 2 given numbers(not inclusive)

1) from random import*


2) for i in range(10):
3) print(uniform(1,10))

Output:
-------
9.578477968323773
7.7350642246780374
2.0572938669434535
1.0902143578722594
8.41020155782424
2.940478753853089
9.726156649079659
2.222538546560088
9.940249578591855
4.218384799153155

random()-> in between 0 and 1 (not inclusive)


randint(x,y) -> in between x and y (inclusive)
uniform(x,y) -> in between x and y (not inclusive)

4) randrange([start],stop,[step])
---------------------------------
- Returns a random number from range
- start <=x<stop
- start argument is optional and default value is 0
- step argument is optional and default value is 1

- randrange(10)-> generates a number from 0 to 9


- randrange(1,11)-> generates a number from 1 to 10
- randrange(1,11,2)-> generates a number from 1,3,5,7,9

1) from random import*


2) for i in range(10):
3) print(randrange(10))

Output:
-------
9
4
0
2
9
4
8
9
5
9

1) from random import*


2) for i in range(10):
3) print(randrange(1,11))

Output:
-------
2
2
8
10
3
5
9
1
6
3

1) from random import*


2) for i in range(10):
3) print(randrange(1,11,2))

Output:
--------
1
3
9
5
7
1
1
1
7
3

5) choice() Function:
----------------------
- It wont't return random number.
- It will return a random object from the given list or tuple.

1) from random import*


2) list=["Sunny","Bunny","chinny","vinny","pinny"]
3) for i in range(10):
4) print(choice(list))

Output:
-------
Bunny
pinny
Bunny
Sunny
Bunny
pinny
pinny
vinny
Bunny
SunnyS

You might also like