1-Core Python Material
1-Core Python Material
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()
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()
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:
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:
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.
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:
and or not is
if elif else
9.Data Types
---How convert the integer values into one base to another base
(by using Base convertion Method)
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
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.
IMPORTANT FEATURES:
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
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
Mutable-changeable:
---------------------------------------
COLLECTION RELATED DATA TYPE:
L=[10,'NARESH',20,10,30]
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
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
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
x=f1()
print(x)
o/p:10
eg:2
def f1():
print('hello')
x=f1()
print(x)
o/p:none
Comments:
// this is single line comments in java
/*---------------
---------------multiline comment in java*/
TYPES OF OPERATORS:-----------------------------------------
Labraries:a group of modules are called as library.
module==> a group of functions,variables,classes
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
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")
EG:4
10<20<30<40==TRUE(ALSO APPLICABLE)
10<20<35<3==FALSE
NOTE:IN JAVA AND C NOTE APPLICABLE
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
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.
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
#read to float values from keyboard which has specified with, separation
and print sum
10.2,10.6
eval():meaning is evaluate
-------
x=eval("10+20+30")
print(x)
O/P: 10+30+50=90
EG:
x=eval(input("Enter some data:")
print(type(x))
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?
o/p:
c:\>py.test.py 100 200 300
the sum=600
eg:
from sys import argv
print(argv[1])
note:if u read total name must enclosed b/w the " " or """ """ not
maintain the '' or ''' '''
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=':')
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='-')
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))
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:
--------------------
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:
syntax:1
if(condition):
statement1
statement2
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")
o/p:12 45
45 is biggest number
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")
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:
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
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
Syntax:
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)
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
*
* *
* * *
* * * *
* * * * *
* * * * * *
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
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
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
WHEN ELSE PART WILL BE EXECUTED WRT LOOPS? IF LOOP EXECUTED WITHOUT BREAK
3) pass statement:
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
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:
---------------
Eg:
x=1
print(x)
del x
x=10
del x
print(x)
s='naresh'
print(s)
del s->valid
dels[0]-> Type error:'str' object does not support item deletion.
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
-------------------------------------------------------------------------
---------------------------------------------------------
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"
Eg:
ch='a'
type(ch)
<class 'string'>
Eg:
s='''Naresh
software
solutions'''
we can also use triple quotes to use single quotes or double quotes as
symbol inside String literal.
Eg:s='Naresh'
>>>s='Naresh'
>>>s[0]
'N'
>>>s[-1]
'h'
>>>s[10]
Index error :String Index out of range
o/p:
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.
***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.
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
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.
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
Finding Substrings:
------------------------------
We can use the fallowing 4 methods
For forward direction:
----------------------
1) find()
2) index()
1)find():
---------
Return index of first occurrence of the given substring. If it is not
available then we will get -1.
Note: By default find() method can search total string.we can also
specify the boundaries to search.
s.find(substring,begin,end)
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.
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
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
s="abcabcabcabcadda"
print(s.count('a'))
print(s.count('ab'))
print(s.count('a',3,7))
output:
6
4
2
Eg:1
s="Learning python is very difficult"
s1=s.replace("difficult","easy")
print(s1)
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
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
output:
-------
True
False
True
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
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)
output:
-------
Input:Learning Pythonis very Easy
output:Easy Very is Python Learning
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
Input: s1="ravi"
s2="teja"
output: rtaevjia
6)
write a program to sort the characters of the string and First alphabet
symbols followed by numaric values:
Input:B4A1D3
output:ABD134
Input:ABCDABBCDABBBCCCDDEEEF
output:ABCDEF
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
11)
write a program to perform the fallowing task:
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:
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.
Eg:3
print Decimal value in binary, octal and hexadecimal form
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.
Output:
Int value with:+123
Int value with sign:-123
Float value with sign:+123.456000
Float value with sign:-123.456000
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
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*
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
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()))
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))
complexNumber=1+2j
print("Real Part:{0.real} and imaginary
Part:{0.imag}".format(complexNumber))
-6 -5 -4 -3 -2 -1
10 A B 20 30 10
0 1 2 3 4 5
[]
<class 'list'>
c:\1>py test.java
Enter List:[10,20,30,40]
[10,20,30,40]
<class,'list'>
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']
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]]
-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
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]
c:1>py test.py
0
2
4
6
8
10
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
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
list=[]
list.append("A")
list.append("B")
list.append("C")
print(list)
c:\1>py test.py
['A','B','C']
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.
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)
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]
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=[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
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
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.
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']
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']
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]
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]
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]
x=["Dog","Cat","Rat"]
y=["Dog","Cat","Rat"]
z=["DOG","CAT","RAT"]
print(x==y)->True
print(x==z)->False
print(x!=z)->True
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.
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]]
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.
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]
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
List out all Functions of List and write a program to use these
Functions.
t=10,20,30,40
print(t)
print(type(t))
output:
(10,20,30,40)
<class 'tuple'>
t=()
print(type(t))->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'>
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.
list=[10,20,30]
t=tuple(list)
print(t)
t=tuple(range(10,20,2))
print(t)
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
t1=(10,20,30)
t2=t1*3
print(t2)->(10,20,30,10,20,30,10,20,30)
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)
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
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.
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?
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
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.
-------------------------------------------------------------------------
--------------------------------------
Output
------
{40,10,20,30}
<class 'set'>
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'>
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}
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}
Output:
-------
{10,20,30}
set()
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}
Set Comprehension:
------------------
set comprehension is possible.
D:\Python_classes>py test.py
enter list of
values:[10,20,30,10,20,40]
[10,20,30,40]
D:\Python_classes>py test.py
Enter word to search for vowels:durga
The different vowel present in durga are{'u','a'}
Note:In c++ and java Dictionaries are known as "Map" where as in Perl and
Ruby It is Known as "Hash"
d={100:'durga',200:'ravi',300:'shiva'}
d={key:value,key:value}
d={100:'durga',200:'ravi',300:'shiva'}
print(d[100]) #durga
print(d[300]) #shiva
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%
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
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
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
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?
-----------------------
output
------
D:\python_classws>py test.py
Enter the number of students:5
Dictionary Comprehension:
--------------------------
Comprehension concept application for dictionaries also.
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.
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..
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.
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
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
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
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)
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 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.
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.
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()
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)
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
Note:
-----
By using lambda Functions we can write very concise code so that
readability of the program will be improved.
Output
-------
The square of 4 is:16
The square of 5 is:25
Output
-----
The Sum of 10,20 is: 30
The Sum of 100,200 is: 300
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.
Filter() Function:
------------------
We can use filter() function to filter values from the given sequence
based on some comdition.
filter(function,sequence)
Q) Program to filter only Even Numbers from the List by using filter()
Function?
-------------------------------------------------------------------------
--------
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.
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
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
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)
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.
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.
test.py:
--------
1) from durgamath import*
2) print(x)
3) add(10,20)
4) product(10,20)
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
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.
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
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")
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_
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
-------
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
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)
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)
3)uniform()Function:
---------------------
It returns random float values between 2 given numbers(not inclusive)
Output:
-------
9.578477968323773
7.7350642246780374
2.0572938669434535
1.0902143578722594
8.41020155782424
2.940478753853089
9.726156649079659
2.222538546560088
9.940249578591855
4.218384799153155
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
Output:
-------
9
4
0
2
9
4
8
9
5
9
Output:
-------
2
2
8
10
3
5
9
1
6
3
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.
Output:
-------
Bunny
pinny
Bunny
Sunny
Bunny
pinny
pinny
vinny
Bunny
SunnyS