Python New Material
Python New Material
com
Contact:9030202723
Module-01(core python)
1) Introduction
2) Language Fundamentals
3) Operators
4) Input and Output Statements
5) Flow Control
6) String Data Structure
7) List Data Structure
8) Tuple Data Structure
9) Set Data Structure
10) Dictionary Data Structure
11) Functions
12) Modules
13) Packages
Introduction:
Python is a widely used general-purpose, high level
programming language. It was created by Guido van Rossum
in 1991 at the Centrum Wiskande & Informatica(CWI) and
further developed by the Python Software Foundation. It was
designed with an emphasis on code readability, and its syntax
allows programmers to express their concepts in fewer lines of
code.
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Identfiers:
A name in the python program is called as identifier.
It can be a class name or function or module name or
variable name.
Ex: a=10
def(): class test:
Variables in python:
Variables are nothing but reserved memory locations to store
values. This means that when you create a variable you
reserve some space in memory.
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Reserved Words:
Note:
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Data Types:
--> Data types are used to specify what type of data has to be
store in the variable.
--> Without specifying data types variable memory allocation
with not take place for variables.
--> Programming languages supports 2-types of data types.
1).Static 2).Dynamic
-->In dynamic data type we not need to specify data type , it will
be define automatically based on user input.
-->Python data types are categorized into 2-parts.
-->Fundamental types
-->Collection types
Python supports three types of numeric data.
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Note:
1) type():
To check the type of variable.
2) id():
To get the address of object.
3) print():
To print the value
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
--> long data type is available in python2 but not in python3. In python3
long values also we can represent by using int type only.
Type Casting:
-->We can convert one type to other type. This conversion is called as
Typecasting or Type coercion.
-->The following are various in-built functions for type casting.
--> int()
--> float()
--> bool()
--> str()
--> bytes()
1) int():
We can use this function to convert values from other types to int.
1. >>> int(123.456)
2. 123
3. >>> int(10+4j)
4. TypeError: can't convert complex to int
5. >>> int(True)
6. 1
7. >>> int(False)
8. 0
9. >>> int("10")
10. 10
11. >>> int("10.5")
12. ValueError: invalid literal for int() with base 10: '10.5'
13. >>> int("ten")
14. ValueError: invalid literal for int() with base 10: 'ten'
15. >>> int("0B1010")
16. ValueError: invalid literal for int() with base 10: '0B1010'
Note:
-->We can convert from any type to int except complex type.
-->If we want to convert str type to int type, compalsury str should
contains only integral value and should be specified in base-10.
2) float():
We can use float() to convert other type values to float type.
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1. >>> float(10)
2. 10.0
3. >>> float(10+4j)
4. TypeError: can't convert complex to float
5. >>> float(True)
6. 1.0
7. >>> float(False)
8. 0.0
9. >>> float("10")
10. 10.0
11. >>> float("10.5")
12. 10.5
13. >>>float("ten")
14. ValueError: could not convert string to float: 'ten'
Note:
--> We can convert any type value to float type except complex
type.
--> Whenever we are trying to convert str type to float type compulsory
str should be either integral or floating point literal and should be
specified only in base-10.
3) bool():
We can use this function to convert other type to bool type
1. >>> bool(0)
2. False
3. >>> bool(1)
4. True
5. >>> bool(10)
6. True
7. >>> bool(0.123)
8. True
4) str():
We can use this method to convert other type values to str type.
1. >>> str(10)
2. '10'
3. >>> str(10.5)
4. '10.5'
5. >>> str(True)
6. 'True'
7. >>> str(10+4j)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
8. '(10+4j)'
1) >>> x=[10,20,30,40]
2) >>> b=bytes(x)
3) >>> type(b)
4) <class 'bytes'>
5) >>> b[0]
6) 10
7) >>> b[-1]
Conclusion 1:
The only allowed values for byte data type are 0 to 256. BY mistakes if
we are trying to provide any other values then we will get value
error.
Ex: >>> x=[10,20,300,40]
>>> b=bytes(x)
ValueError: bytes must be in range (0, 256)
Conclusion 2:
Once we create bytes data type value, we can't change it values, if we
are trying to change we will get an error.
Ex: >>> x=[10,20,30,40]
>>> b=bytes(x)
>>> b[2]=50
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Operators:
Python Operators
Operators are used to perform operations on variables and
values.
Python divides the operators in the following groups:
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
input():
1) x=input(Enter value")
2) type(x)
3) 10==>int
4) "prsoftwares"==>str
5) 10.5==>float
6) True==>bool
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Note:
Ex:
1) >>> x=input ("Enter some value :")
2) Enter some value: 10
3) <Class 'str'>
4) Enter some value: True
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Note:
split() function can take space as separator by default, But we can pass
anything as separator.
eval():
1) >>> x=eval("10+20+30")
2) >>>x
3) >>>60
4)
5) x=eval(input("Enter expression :"))
6) print(x)
7) Enter expression :10+2*3/4
8) 11.5
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Note:
-->split() always accept sting only as a separator.
-->If we are not using eval() then it is treated as str.
Ex:
1) a,b,c=[eval(x) for x in input("Enter 3 values :").split("5")]
2) print(type(a))
3) print(type(b))
4) print(type(c))
Output Streams:
We can use print() function to display output.
Form-2: print(String)
print("Hello world")-->We can use escape characters also
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Ex: print(“prsoftwares”)
print(10*"hello") print("hello"*10)
Note:
--> If both arguments are string type then + operator acts as
concatenation operator.
--> If one argument is string type and second is any other type
like int then we will get an error.
--> If both arguments are number type then + operator avts as
arithmetic addition operator.
Ex:
1) a,b,c=10,20,30
2) print(a,b,c,sep=',')
3) print(a,b,c,sep=':')
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1) print("Hello")
2) print("PR")
3) print("SoftWARES")
o/p: Hello
PR SoftWARES
1) print("Hello",end=' ')
2) print("PR",end=' ')
3) print("Soft")
Form-5:print(object) statement
-->We can pass any object(like list, tuple, set etc) as argument
to the print statement.
Ex:
1) l=[10,20,30,40]
2) t=(10,20,30,40)
3) print(l)
4) print(t)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Form-7:print(formatted string):
%d===>int
%f===>float
%s===>string type
1) a=10
2) b=20
3) c=30
4) print("a value is %d" %a)
5) print("b value is %d and c value is %d" %(b,c))
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
FLOW CONTROL
-->Flow control describes the order in which statements will be
executed at runtime.
Conditional Statements:
1).if:
if condition: statement
or
if condition: statement-1 statement-1 statement-1
--> If condition is true then statements will be executed.
2).if-else:
if condition:
Action-1 else:
Action-2
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
3).if-elif-else: syn:
if condition1:
Action-1
elif condition-2:
Action-2
elif condition-3:
Action-3 else
Action-3
Syntax:
S=”prsoftwares”
s.replace(oldstring,newstring)
ex-s.replace(“s”,”ss”)
--> Inside s, every occurance of old string will be replaced with
new string.
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Splitting of string:
Joining of Strings:
-->We can join a group of strings (list or tuple) wrt the given
separator. Syn: s=separator.join(group of strings)
Ex:
1) t=('prsoftwares','premsofts','belongs to Mr.Prem')
2) s='-'.join(t)
3) print(s)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
--> List objects are mutable. i.e we can change the content.
Ex: list=[ ]
print(list)
print(type(list))
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1) list=eval(input("Enter List:"))
2) print(list)
3) print(type(list))
1) l=list(range(10))
2) print(l)
3) print(type(l))
Syn:
list2=list1[start:stop:step]
start-->It indicates the index where slice has to start. default
value is 0.
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
List Vs mutability:
1) n=[0,1,2,3,4,5,6,7,8,9,10]
2) i=0
3) while i<len(n):
4) print(n[i])
5) i=i+1
1) n=[0,1,2,3,4,5,6,7,8,9,10]
2) for i in n:
3) print(i)
1) n=[0,1,2,3,4,5,6,7,8,9,10]
2) for i in n:
3) if i%2==0:
4) print(i)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1. len():
Returns number of elements present in the list.
Ex:
1) l=[10,20,30,40]
2) len(l)==>4
2. count():
It returns the number of occurences of specified item in the list
Ex:
1) n=[1,2,2,2,2,3,3]
2) print(n.count(1))==>1
3) print(n.count(2))==>4
4) print(n.count(3))==>2
3. index():
It returns index of first occurance of the specified element.
Ex:
1) l=[1, ,2,3,3,4]
2) print(l.index(1))==>0
3) print(l.index(2))==>1
4) print(l.index(3))==>3
5) print(l.index(4))==>5
Note:
If the specified element not present in the list then we will get
ValueError. Hence
before index() method we have to check whether item present
in the list or not by using in operator.
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
We can use append() function to add item at the end of the list.
Ex:
1) l=[ ]
2) l[]
3) l.append("A")
4) l.append("B")
5) l.append("C")
6) l
['A', 'B', 'C']
Ex: To add all elements to list upto 100 which are divisible by10
1) list=[ ]
2) for i in range(101):
3) if i%10==0:
4) list.append(i)
5) print(list)
2).insert() function:
To insert an item at specified index position.
Ex:
1) >>> n=[1,2,3,4]
2) >>> n.insert(1,333)
3) >>> n [1, 333, 2, 3, 4]
In list when we add any element it will come in last. i.e it will be
last element. insert():
In list we can insert any element in a particular index number
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Note:
3).extend() function:
--> To add all items of one list to another list. Syn: l1.extend(l2)
--> All items present in l2 will be added to l1.
Ex:
1) order1=["Python","Java",".Net"] 2)
order2=["RC","KF","FO"]
3) order1.extend(order2)
4) print(order1)
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.
Ex:
1) n=[10,20,30,10,30]
3) print(n)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Note:
Hence before using remove() method first we have to check
specified element present in the list or not by using in operator.
Ex:
1) l=[10,20,30,40,10,30]
2) x=int(input("Enter element to be removed:"))
3) if x in l:
4) l.remove(x)
5) print("Removed successfully...")
6) else:
7) print("Specified element is not available")
5).pop() function:
1) n=[ ]
2) print(n.pop())
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Note:
remove() pop()
1.We can use to remove 1.We can use to remove
Specified element from the last element.
list
2.It can't return any value. 2.It returned removed
element
Note:
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1) n=[10,20,30,40]
2) n.revrse()
3) print(n)
o/p: [40,30,20,10]
2. sort() function:
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.
Ex:
1) n=[20,10,40,30]
2) n.sort()
3) print(n)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
o/p:[10,20,30,40]
To sort in reverse of default natural sorting order:
-------------------------------------------------------------------
---
-->We can sort according to reverse of default
natural sorting order by using reverse=True
argument.
Ex:
1) n=[10,30,20,40]
2) n.sort()
3) print(n)==>[10,20,30,40]
4) n.sort(reverse=True)
5) print(n)==>[40,30,2010]
6) n.sort(reverse=False)
7) print(n)==>[10,20,30,40]
1) x=[10,20,30,40]
2) y=x
3) y[1]=333
4) print(x)
5) print(y)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
o/p:D:\pythonclasses>py test.py
[10, 333, 30, 40]
[10, 333, 30, 40]
1).By using slice operator:
-------------------------------------
Ex:
1) x=[10,20,30,40]
2) y=x[:]
3) y[1]=333
4) print(x)
5) print(y)
o/p:D:\pythonclasses>py test.py
[10, 20, 30, 40]
[10, 333, 30, 40]
1) x=[10,20,30,40]
2) y=x.copy()
3) y[1]=333
4) print(x)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1).Concatenation operator(+):
We can use + to concatinate 2 lists into a single
list.
Ex:
1) a=[10,20,30]
2) b=[40,50,60]
3) c=a+b
4) print("c:",c)
Ex:
o/p:D:\pythonclasses>py test.py
c: [10, 20, 30, 40, 50, 60]
1) a=[10,20,30]
2) b=[40,50,60]
3) c=a.extend(b)
4) print("a:",a)
5) print("b:",b)
6) print("c:",c)
Note:
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
2).Repetition operator(*):
-----------------------------------
We can use repetition operator * to repeat the
elements of list specified number of
times.
Ex:
1) x=[10,20,30]
2) y=x*3
3) print(y)==>[10,20,30,10,20,30]
1) x=["Dog","Cat","Rat"]
2) y=["Dog","Cat","Rat"]
3) z=["DOG","CAT","RAT"]
4) print(x==y)==>True
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
5) print(x==z)==>False
6) print(x!=z)==>True
clear() function:
-----------------------
We can use clear() function to remove all elements
of list.
Ex:
1) n=[10,20,30,40]
2) print(n)
3) n.clear()
4) print(n)
Nested Lists:
============
Sometimes we can take one list inside another list.
Such type of lists are called as nested lists.
Ex:
1) n=[10,20,[30,40]]
2) print(n)
3) print(n[0])
4) print(n[1])
5) print(n[2][0])
6) print(n[2][1])
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Ex:
1. t=10,20,30,40
2. print(t)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
3. print(type(t))
t=()
print(type(t))==>tuple
1. t=10
2. print(t)
3. print (type(t))
Tuple Creation:
---------------------
1.t=():
Creation of empty tuple
2.t=(10,) or t=10,
Creation of single valued tuple, paranthesis are
optional, should ends with comma.
3.t=10,20,30 or t=(10,20,30)
Creatin of multiple values tupl & parenthesis are
optional.
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1. l=[10,20,30,40]
2. t=tuple(l)
3. print(t)
4. print(type(t))
Accessing elements of tuple:
==========================
We can access either by index or by using slice
operator.
1. By using index:
1. t=(10,20,30,40)
2. print(t[0])==>10
3. print(t[-1])==>40
4. print(t[100])==>IndexError
1. t=(10,20,30,40,50,60)
2. print(t[2:5])
3. print(t[2:100])
4. print(t[::2])
o/p:
(30, 40, 50)
(30, 40, 50, 60)
(10, 30, 50)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Tuple Vs immutability:
====================
-->Once we create tuple, we can't change its
content.
-->Hence tuple objects are immutable. Ex:
1. t=(10,20,30,40,50)
2. t[1]=60==>TypeError: 'tuple' objects does not
support item assignment.
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Ex:
1. t=(10,20,30,40)
2. len(t)==>4
2. count():
To return number of occurences of given element
in the tuple.
Ex:
1. t=(10,20,30,10,10)
2. t.count(10)==>3
3).index():
-->Returns index of first occurence of the given
element.
-->If the specified element is not available then we
will get ValueError.
Ex:
1. t=(10,20,30,30,10,40)
2. t.index(30)==>2
3. t.index(50)==>ValueError
4. sorted():
To sort elements based on default natural sorting
order.
Ex:
1. t=(40,20,50,10,30)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
2. t1=sorted(t)
3. print(t)
4. print(t1)
Ex:
o/p:
(40, 20, 50, 10, 30)
[10, 20, 30, 40, 50]==>After sorting it will return as
list
1. t=(40,20,50,10,30)
2. t1=tuple(sorted(t))
3. print(t)
4. print(t1)
o/p:
(40, 20, 50, 10, 30)
(10, 20, 30, 40, 50)
Ex:
1. t1=sorted(t,reverse=True)
2. print(t1)==>[50,40,30,20,10]
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1. t=(40,20,50,10,30)
2. print(min(t))==>10
3. print(max(t))==>50
Ex:
1. t="Prsoftwares"
2. print(min(t))==>a
3. print(max(t))==>w
6. cmp():
-->It compares the elements of both tuples.
-->If both tuples are equal then returns 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
Note: cmp() function is available only in python-2
but not in python-3
1. a=10
2. b=20
3. c=30
4. d=40
5. t=a,b,c,d
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
6. print(t)
1. t=(10,20,30,40)
2. a,b,c,d=t
3. print("a=",a,"b=",b,"c=",c,"d=",d)
Note:
o/p:
a= 10 b= 20 c= 30 d= 40
1. t=(10,20,30,40)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
2. a,b,c=t
3. print("a=",a,"b=",b,"c=",c)
Difference between List and Tuple
List Tupl
e
1.List a group of comma 1.Tuple is a group of
separated values within square comma separated values
brackets and square brackets within parenthesis
are mandatory. parenthesis are optional.
Ex: l=[10,20,30] Ex: t=(10,20,30) or t=10,20,30
2.List objects are mutable 2.Tuple objects are
i.e once we creates list immutable i.e once we
object we can perform any creates tuple objects we
changes in that object. can't change it
ex:l[1]=50 content.
Ex:t[1]=50-->ValueError
3.If the content is not fixed 3.If the content is fixed and
and keep on never
changing then we should go changes then we should go
for list. for tuple.
4.Comprehensions are 4.There is no
available. comprehensions.
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
on our requirement.
-->We can represent set elements with curly
braces and with comma separation.
-->We can apply mathematical operations like
union, intersection, difference etc on set objects.
1. s={10,20,30,40}
2. print(s)
3. print(type(s))
o/p:
{40,10,20,30}
<class 'set'>
Ex:
Ex:
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
l=[10,20,30,40,10,20]
s=set(l)
print(s)
s=set(range(5))
print(s)
1. s=set()
2. print(s)
3. print(type(s))
o/p:
set()
<class 'set'>
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1. s={10,20,30}
2. s.add(40)
3. print(s)
2. update(x,y,z):
-->To add mutiple items to the set.
-->Arguments are not individual elements and
these are iterable elements like list, range etc..
-->All elements present in the given iterable
objects will be added to the set.
Ex:
1. s={10,20,30}
2. l=[40,50,60]
3. s.update(l,range(5))
4. print(s)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
s.add(10,20,30) Invalid
s.update(30) Invalid
s.update(range(1,10,2),range(0,10,2)) Valid
3. copy():
-->Returns copy of the set
-->It is cloned object.
Ex:
1. s={10,20,30}
2. s1=s.copy()
3. print(s1)
4. pop():
It removes and returns some random element from
the set.
Ex:
o/p:
{40, 10, 20, 30}
40
{10, 20, 30}
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
5. remove(x):
-->It removes specified element from the set.
-->If the specified element not present in the set
then we will get KeyError. Ex:
1. s={40,20,30,10}
2. s.remove(30)
3. print(s)==>{40,20,10}
4. s.remove(50)==>KeyError:50
6. discard(x):
-->It removes specified element from the set.
-->If the specified element not present in the set
then we won't get any error. Ex:
1. s={40,20,30,10}
2. s.discard(30)
3. print(s)==>{40,20,10}
4. s.discard(50)
5. print(s)==>{40,20,30,10}
7. clear():
-->To remove all elements from the set. Ex:
1. s={10,20,30}
2. print(s)
3. s.clear()
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
4. print(s)
o/p:
{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.
Syn: x.union(y) or x|y Ex:
1. x={10,20,30,40}
2. y={30,40,50,60}
3. print(x.union(y))#{40, 10, 50, 20, 60, 30}
4. print(x|y) #{40, 10, 50, 20, 60, 30}
2).intersection():
x.intersection(y) or x & y
-->Returns common elements present in both x
and y Ex:
1. x={10,20,30,40}
2. y={30,40,50,60}
3. print(x.intersection(y))#{40, 30}
4. print(x&y)#{40, 30}
3).difference():
x.difference(y) or x-y
-->Returns the elements present in x but not in y.
Ex:
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1. x={10,20,30,40}
2. y={30,40,50,60}
3. print(x.difference(y))#{10, 20}
4. print(x-y)#{10, 20}
5. print(y-x)#{50, 60}
4).symmetric_difference():
x.symmetric_difference(y) or x^y
-->Returns element present in either x or y but not
in both. Ex:
1. x={10,20,30,40}
2. y={30,40,50,60}
3. print(x.symmetric_difference(y))#{10, 50, 20,
60}
4. print(x^y)#{10, 50, 20, 60}
1. s=set("premsofts")
2. print(s)
3. print('p' in s)
4. print('z' in s)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Set comprehension:
----------------------------
-->set comprehension is possible.
1. s={10,20,30,40}
2. print(s[0]) TypeError: 'set' object does not
support indexing
3. print(s[1:3]) TypeError: 'set' object does not
support indexing
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Approach-2:
6. print(l1)
o/p:
D:\pythonclasses>py test.py
Enter List Of Values:[10,20,20,10,30,40] [10, 20,
30, 40]
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Ex:
rollno-----name
phone number---address
ip address----domain name
product name----price
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Note:
In C++ and java Dictionaries are known as "Map"
where as in perl and Ruby it is
known as "Hash"
1. d={}
2. d1=dict()
3. print(type(d))
4. d[100]="Prsoftwares"
5. d[200]="Premsofts"
6. d[300]="Prem"
7. print(d)#{100: 'Prsoftwares', 200: 'Premsofts',
300: 'Prem'}
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
d={100:"Prsoftwares",200:"Premsofts",300:"Prem"}
print(d[100])==>Prsoftwares print(d[300])==>Prem
Ex:
if 400 in d:
print(d[400])
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1. rec={ }
2. n=int(input("Enter Number Of Students: "))#3
3. i=1
4. while i<=n:
5. name=input("Enter Student Name:")
6. marks=int(input("Enter % of Marks:"))
7. rec[name]=marks
8. i=i+1
9. print("Name of the student","\t","% of marks")
10. for x in rec:
11. print("\t",x,"\t\t",rec[x])
1.
d={100:"Prsoftwares",200:"Premsofts",300:"Pr
em"}
2. print(d)
3. d[400]="python"
4. print(d)
5. d[100]="JAVA"
6. print(d)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
del d[key]:
---------------
It deletes entry associated with the specified key.
If the key is not available then we will get
KeyError.
Ex:
1.
d={100:"Prsoftwares",200:"Premsofts",300:"Pr
em"}
2. print(d)
3. del d[300]
4. print(d)
5. del d[400]
6. print(d)
d.clear():
------------
To remove all entries from the dictionary.
Ex:
1.
d={100:"Prsoftwares",200:"Premsofts",300:"Pr
em"}
2. print(d)
3. d.clear()
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
4. print(d)
o/p:D:\pythonclasses>py test.py
{100: 'Prsoftwares', 200: 'Premsofts', 300: 'Prem'}
{}
del d:
--------
Ex:
1.
d={100:"Prsoftwares",200:"Premsofts",300:"Pr
em"}
2. print(d)
3. del d
4. print(d)
o/p:D:\pythonclasses>py test.py
{100: 'Prsoftwares', 200: 'Premsofts', 300: 'Prem'}
NameError: name 'd' is not defined
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1).dict():
To create a dictionary. d=dict()==>It creates empty
dictionary
1.
d=dict({100:"Prsoftwares",200:"Premsofts"})==
>It creates dictionary with specified elemen
ts
2. print(d)
3.
d=dict([(100,"Prsoftwares"),(200,"Premsofts")])
==>It creates a dictionary with the given lis
t of tuple lements.
4. print(d)
5.
d=dict(((100,"PRSOFTWARES"),(200,"PREM
SOFTS")))==>It creates a dictionary with the given
tuple of tuple lements.
6. print(d)
o/p:D:\pythonclasses>py test.py
{100: 'Prsoftwares', 200: 'Premsofts'}
{100: 'Prsoftwares', 200: 'Premsofts'}
{100: 'PRSOFTWARES', 200: 'PREMSOFTS'}
2).len():
Returns the number of items in the dictionary.
3).clear():
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
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 available then returns the
corresponding value otherwise returns default
value.
Ex:
1.
d={100:"Prsoftwares",200:"Premsofts",300:"Pr
em"}
2. print(d[100])#Prsoftwares
3. print(d[400])#KeyError:400
4. print(d.get(300))#Prem
5. print(d.get(400))#None
6. print(d.get(100,"Guest"))#Prsoftwares
7. print(d.get(400,"Guest"))#Guest
5).pop():
d.pop(key):
It removes the entry associated with the specified
key and returns the corresponding value.
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1.
d={100:"Prsoftwares",200:"Premsofts",300:"Pr
em"}
2. print(d)
3. print(d.pop(300))
4. print(d)
5. d.pop(400)
o/p:D:\pythonclasses>py test.py
{100: 'Prsoftwares', 200: 'Premsofts', 300: 'Prem'}
Prem
{100: 'Prsoftwares', 200: 'Premsofts'}
KeyError: 400
6).popitem():
It removes an arbitrary item(key-value) from the
dictionary and return it.
Ex:
1.
d={100:"Prsoftwares",200:"Premsofts",300:"Pr
em"}
2. print(d)
3. print(d.popitem())
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
4. print(d)
o/p:D:\pythonclasses>py test.py
{100: 'Prsoftwares', 200: 'Premsofts', 300: 'Prem'}
{100: 'Prsoftwares', 200: 'Premsofts'}
7).keys():
It returns all keys associated with dictionary.
Ex:
1.
d={100:"Prsoftwares",200:"Premsofts",300:"Pr
em"}
2. print(d.keys())
3. for k in d.keys():
4. print(k)
8).values():
It returns all values associated with dictionary.
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Ex:
1.
d={100:"Prsoftwares",200:"Premsofts",300:"Pr
em"}
o/p:D:\pythonclasses>py test.py
dict_values(['Prsoftwares', 'Premsofts', 'Prem'])
Prsoftwares
Premsofts Prem
9).items():
It returns list of tupes represented key-value pairs.
[(k,v),(k,v),(k,v)]
Ex:
1.
d={100:"Prsoftwares",200:"Premsofts",300:"Pr
em"}
3. print(k,"--",v)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
10).copy():
To create exactly duplicate dictionary (cloned
copy)
Ex:
1.
d={100:"Prsoftwares",200:"Premsofts",300:"Pr
em"}
2. d1=d.copy()
3. print(id(d))
4. print(id(d1))
11).setdefault(): d.setdefault(k,v)
-->If the key is already available then this function
returns the corresponding value.
-->If the key is not available then the specified key-
value will be added as new item to the dictionary.
Ex:
1.
d={100:"Prsoftwares",200:"Premsofts",300:"Pr
em"}
2. print(d.setdefault(400,"secunderabad"))
3. print(d)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
5. print(d)
12).update(): d.update(x)
All items in the dictionary x will added to dictionary
d.
Ex:
1.
d={100:"Prsoftwares",200:"Premsofts",300:"Pr
em"}
2. d1={'a':"apple",'b':"banana",'c':"cat"}
3. d.update((d1))
4. print(d)
5. d.update([(333,"A"),(999,"B")])
6. print(d)
o/p:D:\pythonclasses>py test.py
{100: 'Prsoftwares', 200: 'Premsofts', 300: 'Prem',
'a': 'apple', 'b': 'banana', 'c': 'cat'}
{100: 'Prsoftwares', 200: 'Premsofts', 300: 'Prem',
'a': 'apple', 'b': 'banana', 'c': 'cat', 333: 'A', 999: 'B'}
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1. d=eval(input("Enter Dictionary:"))
3. print("Sum:",s)
o/p:D:\pythonclasses>py test.py
Enter Dictionary:{'A':100,'B':200,'C':300} Sum: 600
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Dictionary comprehension:
---------------------------------------
-->Comprehension concept applicable for
dictionary also. Ex:
o/p:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
FUNCTIONS
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
-->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
s/w automatically, are called as built in functions or
pre-defined functions.
Ex:
id(), type(), input(), eval().........
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
------
-----
return value
Note: while creating functions we can use 2
keywords 1.def(mandatory)
2. return(optional)
1. def wish():
2. print("Hello gud mng.............")
3. 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
we will get error.
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1. def wish(name):
2. print("Hello", name," gud mng.............")
3. wish("Premsofts")
4. wish("Guest")
1. def squareit(number):
2. print("the square of", number," is:",number**2)
3. squareit(4)
4. squareit(5)
Return Statement:
--------------------------
Function can take input values as parameters and
executes business logic, and returns output to the
caller with the return statement.
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1. def add(x,y):
3. result=add(10,20)
1. def f1():
2. print("hello")
3. f1()
4. print(f1())
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
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)
1. def fact(num):
2. result=1
3. while num>=1:
4. result=result*num
5. num=num-1
6. return result
7. print(fact(5))
8. for i in range(1,5):
9. print("The factorial ",i,"is",fact(i))
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
The factorial 4 is 24
Ex:
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("sum is: ",x)
7. print("sub is: ",y)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Types of arguments:
-----------------------------
def f1(a,b):
--------
--------
--------- f1(10,20)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1.positional arguments:
----------------------------------
These are the arguments passed to function in
correct positional order Ex:
1. def sub(a,b):
2. print(a-b)
3. sub(100,200)
4. sub(200,100)
2).keyword arguments:
--------------------------------
We can pass argument values by keyword i.e by
parameter name. Ex:
1. def wish(name,msg):
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
2. print("Hello",name,msg)
3. wish(name="Prsoftwares",msg="gud mng....")
4. wish(msg="gud mng....",name="Prsoftwares")
Note:
We can use both positional and keyword
arguments simultaneously. But first we
have to take positional arguments and then take
keyword arguments, otherwise we will get an error.
Ex:
1. def wish(name,msg):
2. print("Hello",name,msg)
3. wish("Prsoftwares","Gud Mng......")==>Valid
4. wish("Prsoftwares",msg="Gud
Mng.....")==>Valid
5. wish(name="Prsoftwares","Gud
Mng........")==>Invalid
o/p:SyntaxError: positional argument follows
keyword argument
3.Default argument:
----------------------------
Sometimes we can provide default values for our
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1. def wish(name="Prsoftwares"):
2. print("Hello",name,"Gud Mng.....")
3. wish()
4. wish("Premsofts")
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1. def sum(*n):
2. total=0
3. for i in n:
4. total=total+i
5. print("Sum is:",total)
6. sum()
7. sum(10,20)
8. sum(10,20,30)
9. sum(10,20,30,40)
Types of Variables:
--------------------------
Python supports two types of variables.
-->Global Variable
-->Local Variable
Global variable:
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
----------------------
-->The variables which are declared outside the
function are called as global variables.
-->These variables can be accessed in all
functions of that module.
Ex:
1. a=10#global variable
2. def f1():
3. print('f1:',a)
4. def f2():
5. print('f2:',a)
6. f1()
7. f2()
o/p: 10
10
Local Variable:
---------------------
-->The variables which are declared inside a
function are called as local variables.
-->Local variables are available only for the
function in which we declared it. i.e from outside of
function we can't access.
Ex:
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1. def f1():
2. a=10
3. print('f1:',a)
4. def f2():
5. print('f2:',a)
6. f1()
7. f2()
o/p: f1: 10
NameError: name 'a' is not defined
global keyword:
----------------------
We can use global keyword for the following 2
purposes
-->To delcare global variable inside a function.
-->To make global variable available to the
function so that we can perform required
modifications.
Ex:
1. a=10
2. def f1():
3. a=333
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
4. print('f1:',a)
5. def f2():
6. print('f2:',a)
7. f1()
8. f2()
Ex:
1. a=10#global
2. def f1():
3. global a
4. a=333#local
5. print('f1:',a)
6. def f2():
7. print('f2:',a)
8. f1() f2()
9. f2() f1()
o/p:D:\pythonclasses>py test.py
o/p:D:\pythonclasses>py test.py f1: 333 f2:
f2: 333 f1: 333
Ex:
1. def f1():
2. global a
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
3. a=10
4. print('f1:',a)
5. def f2():
6. print('f2:',a)
7. f1()
8. f2()
Ex:
1. a=10#global variable
2. def f1():
3. a=333#local variable
4. print('f1:',a)
5. print(globals()['a'])
6. f1()
Recursive Functions:
------------------------------
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Ex: factorial(3):
3*factorial(2)
3*2*factorial(1)
3*2*1*factorial(0)
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 0 is: ",factorial(0))
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Anonymous Functions:
=====================
-->Sometimes we can declare a function without
name, such type of nameless functions are called
as anonymous functions or lamda functions.
-->The main advantage of anonymous function is
just for instant use(i.e for one time usage)
Normal Function:
-------------------------
-->We can define by using def keyword.
def squareit(n):
return n*n
lambda function:
------------------------
-->We can define by using lambda keyword.
lambda n:n*n
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
-----------------------------
1. s=lambda n:n*n
2. print("The square of 3 is:",s(3))
3. print("The square of 5 is:",s(5))
1. s=lambda a,b:a+b
2. print("The sum of 10 and 20 is:",s(10,20))
3. print("The sum of 100 and 200 is:",s(100,200))
o/p:D:\pythonclasses>py test.py
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Note:
Lambda function internally returns expression
value and we are not required to
write return statement explicitly.
Some times we can pass function as argument to
another function. In such case lambda functions
are best choice.
1).filter function:
------------------------
We can use filter() function to filter values from the
given sequence based on some condition.
Syn:
filter(function,sequence)
-->Where function argument is responsible to
perform conditional check sequence can be list or
tuple or string.
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1. def isEven(n):
2. if n%2==0:
3. return True
4. else:
5. return False
6. l=[0,5,10,15,20,25,30]
7. print(type(filter(isEven,l)))
9. print(l1)
o/p:D:\pythonclasses>py test.py
<class 'filter'> [0, 10, 20, 30]
1. l=[0,5,10,15,20,25,30]
2. l1=list(filter(lambda x:x%2==0,l))
3. print(l1)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
4. l2=list(filter(lambda x:x%2!=0,l))
5. print(l2)
2).map() function:
---------------------------
For every element present in the given sequenece,
apply some functionality and generate new
element with the required modifications. For this
requirement we should go for map() function.
Syn:
map(function,sequenec)
-->The function can be applied on each element of
sequence and generates new sequence.
without lambda:
----------------------- l=[1,2,3,4]
l1=[]
for i in l:
l1.append(i*2)
print(l1)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
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]
3).reduce() function:
-----------------------------
reduce() function reduces sequence of elements
into a single element by applying the specified
function.
Syn:
reduce(function, sequence)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
o/p:150
Ex:
o/p:12000000
Ex:
o/p:5050
Function Decorators
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Input function-------->
Decorator Function---------->o/p function with
extended fun
Ex :
def wish(name):
print("Hello",name,"Good morning.........")
Ex:
----
1) def decor(func):
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
2) def inner(name):
3) if name=="Prem":
4) print("Hello Prem how is your health.....")
5) else:
6) func(name)
7) return inner
8) @decor
9) def wish(name):
10) print("Hello",name,"Good morning.........")
11) wish("Prsoftwares")
12) wish("Premsofts")
13) wish("Prem")
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1) def mygen():
2) yield 'A'
3) yield 'B'
4) yield 'C'
5) g=mygen()
6) print(type(g))
7) print(next(g))
8) print(next(g))
9) print(next(g))
o/p:D:\pythonclasses>py test.py
<class 'generator'> A
BC
Ex-2:
-------
1) def countdown(num):
2) print("start countdown")
3) while (num>0):
4) yield num
5) num=num-1
6) values=countdown(5)
7) for i in values:
8) print(i)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
o/p:D:\pythonclasses>py test.py 1
2
3
4
5
Generators
-->Generator is a function which is responsible to
generate a sequence of values.
-->We can write generator function just like
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1) def mygen():
2) yield 'A'
3) yield 'B'
4) yield 'C'
5) g=mygen()
6) print(type(g))
7) print(next(g))
8) print(next(g))
9) print(next(g))
o/p:D:\pythonclasses>py test.py
<class 'generator'> A
BC
Ex-2:
-------
1) def countdown(num):
2) print("start countdown")
3) while (num>0):
4) yield num
5) num=num-1
6) values=countdown(5)
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
7) for i in values:
8) print(i)
o/p:D:\pythonclasses>py test.py 1
2
3
4
5
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1) def fib():
2) a,b=0,1
3) while True:
4) yield a
5) a,b=b,a+b
6) for x in fib():
7) if x>100:
8) break
9) print(x)
o/p:D:\pythonclasses>py test.py 0 1 1 2 3 5 8 13
21 34 55 89
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
MODULES
-->A group of functions, variables and classes
saved into a file, which is nothing but module.
-->Every python file(.py) acts as module.
-->Advantages of modules are: Reusability,
Readability & Maintainability.
Ex: prsoftwaresmath.py
----------------------------
1) x=333
2) def add(a,b):
3) return a+b
4) def product(a,b):
5) return(a*b)
-->py prsoftwaresmath.py
-->prsoftwaresmath module contains one variable
and 2 functions.
-->If we want to use memebers of the module in
our program then we should import that module.
import modulename
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1) import prsoftwaresmath
2) print(prsoftwaresmath.x)
3) print(prsoftwaresmath.add(10,20))
4) print(prsoftwaresmath.product(10,20))
o/p: 333
30
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
pycache folder
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
test.py
---------
1) import prsoftwaresmath as m
2) print(m.x)
3) print(m.add(10,20))
4) print(m.product(10,20))
from......import:
----------------------
-->We can import a particular member of module
by using from....import
-->The main advantage of this is we can access
memebrs directly without using module name.
Ex:
----
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
----
member aliasing:
------------------------
Ex:
1) import modulename
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
2) import module1,module2,module3
3) import module1 as m
4) import module1 as m1,module2 as
m2,module3 as m3
5) from module import memeber
6) from module import
memeber1,member2,member3
7) from module import memeber1 as x
8) from module import *
Reloading a Module:
----------------------------
-->Bydefault module will be loaded only once
eventhough we are importing multiple times.
Ex: 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")
o/p:
This is from module1 This is from test module
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Ex:
-----
1) import time
2) import module1
3) print("program entering into sleeping state")
4) time.sleep(30)
5) import module1
6) print("This is last line of the program")
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Ex:
----
1) import time
2) from imp import reload
3) import module1
4) print("program entering into sleeping state")
5) time.sleep(30)
6) reload(module1)
7) print("program entering into sleeping state")
8) time.sleep(30)
9) reload(module1)
10) print("This is last line of the program")
o/p:
This is from module1
program entering into sleeping state This is first
module1
program entering into sleeping state This is
second module1
This is last line of the program
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
-------------------------------------------------------------------
------
-->Python provides inbuilt function dir() to list out
all the members of current module or a specified
module.
Ex:test.py
--------------
1) x=333
2) def add(a,b):
3) return a+b
4) print(dir())
o/p:D:\pythonclasses>py test.py
[' annotations ', ' builtins ', ' cached ', ' doc ', '
file ', ' loader ', ' name ', ' package ', ' spec ',
'add', 'x']
Ex-2: To display members of a particular module.
prsoftwaresmath.py
----------------------
1) x=333
2) def add(a,b):
3) return a+b
4) def product(a,b):
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
5) return(a*b)
test.py
---------
1) import prsoftwaresmath
2) print(dir(prsoftwaresmath))
o/p:D:\pythonclasses>py test.py
[' builtins ', ' cached ', ' doc ', ' file ', ' loader ', '
name ',
' package ', ' spec ', 'add', 'product', 'x']
Ex: ' builtins ', ' cached ', ' doc ', ' file ', '
loader ', ' name ', ' package ', ' spec ',
-->Based on our requirement we can access these
properties also in our program. Ex: test.py
---------------
1) print( builtins )
2) print( cached )
3) print( doc )
4) print( file )
5) print( loader )
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
6) print( name )
7) print( package )
8) print( spec )
o/p:D:\pythonclasses>py test.py
<module 'builtins' (built-in)> None
None test.py
<_frozen_importlib_external.SourceFileLoader
object at 0x000001F562583CF8>
main None None
Ex: module1.py
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
----------------------
1) def f1():
2) if name ==" main ":
3) print("The code executed directly as a
program")
4) print("The value of name :", name )
5) else:
6) print("The code executed indirectly as a
module from some other module")
7) print("The value of name :", name ) 8) f1()
test.py
----------
1) import module1
2) module1.f1()
o/p:D:\pythonclasses>py test.py
The code executed indirectly as a module from
some other module The value of name : module1
The code executed indirectly as a module from
some other module The value of name : module1
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Ex:
----
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
1).random():
-----------------
This function always generates some float value
between 0 and 1(not inclusive).
0<x<1
Ex:
o/p:D:\pythonclasses>py test.py
0.7690917847505055
0.12958902402812178
0.4865336117685294
0.21174369485166067
0.22533721686631736
0.24270745076560807
0.6156350105877338
0.3588237251403473
0.5609192891678808
0.46565274922504374
2).randint():
-----------------
To generate random integer between two given
numbers(inclusive) Ex:
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
o/p:D:\pythonclasses>py test.py 70
88
20
73
16
8
27
72
80
71
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
689042
735553
3).uniform():
------------------
-->It returns random float values between 2-given
numbers(not inclusive)
Ex:
-----
o/p:D:\pythonclasses>py test.py
1.456481671599132
8.262379808015648
8.294591177579873
2.4766196390802415
3.9929683121049644
6.908124318470733
5.113015507787097
1.9677692845675518
8.48400436311528
7.760067312991328
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
4).randrange([start],stop,[step]):
--------------------------------------------
-->Returns a random number from the range.
start<=x<stop
-->start argument is optional and default value is 0.
-->step argument is optional and default value is 1.
Ex 1:
-------
Ex 2:
--------
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Ex 3:
--------
5).choice():
---------------
-->It wont return random number.
-->It will return a random object from the given list
or tuple,str.
Ex 1:
-------
Ex 2:
-------
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
Ex 3:
-------
o/p:D:\pythonclasses>py test.py
TypeError: 'set' object does not support indexing
Ex 4:
-------
3)
print(chr(randint(65,65+25)),randint(0,9),chr(ra
ndint(65,65+25)),randint(0,9
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
),chr(randint(65,65+25)),randint(0,9),sep='')
PACKAGES
Ex1:
-----
D:\pythonclasses
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
|--test.py
|--pack1
|-module1.py
|- init .py
init .py:
----------------
empty file.
module1.py:
------------------
def f1():
print("Hello this is from module1 present in pack1")
test.py(version-1):
-------------------------
import pack1.module1 pack1.modul1.f1()
test.py(version-2):
-------------------------
from pack1.module1 import f1 f1()
Ex 2:
-------
D:\pythonclasses
|--test.py
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
|--com
init .py:
----------------
|--module1.py
|-- init .py
|--prsoft
|--module2.py
|-- init .py
empty file
module1.py:
-----------------
def f1():
print("Hello this is from module1 present in com")
module2.py:
-----------------
def f2():
print("Hello this is from module 2 present in
com.prsoft")
test.py:
By Mr.Prem Agarwal
PRSOFTWARE CORE PYTHON MATERIAL
----------
o/p:
Hello this is from module1 present in com
Hello this is from module 2 present in com.prsoft
By Mr.Prem Agarwal