0% found this document useful (0 votes)
31 views105 pages

2 Python Jul08 To Aug09

Uploaded by

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

2 Python Jul08 To Aug09

Uploaded by

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

==============================================

2. for loop or for ...else loop


==============================================
Syntax1:-
-----------
for varname in Iterable_object:
----------------------------------------
Indentation block of stmts
----------------------------------------
-------------------------------------------------
Other statements in Program
-------------------------------------------------

---------------
Syntax2:
---------------
for varname in Iterable_object:
----------------------------------------
Indentation block of stmts
----------------------------------------
else:
----------------------------------------
else block of statements
----------------------------------------
-------------------------------------------------
Other statements in Program
-------------------------------------------------

Explanation:
-----------------------
=>Here 'for' and 'else' are keywords
=>Here Iterable_object can be Sequence(bytes,bytearray,range,str),
list(list,tuple),set(set,frozenset) and dict.
=>The execution process of for loop is that " Each of Element of Iterable_object selected,placed in
varname and executes Indentation block of statements".This Process will be repeated until all elements of
Iterable_object completed.
=>After execution of Indentation block of statements, PVM executes else block of statements which are
written under else block and later PVM executes Other statements in Program.
=>Writing else block is optional.

Examples:
------------
#Factorsex.py
n=int(input("Enter a number:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
print("="*50)
print("Factors of {}".format(n))
print("="*50)
i=1
while(i<=n//2):
if(n%i==0):
print("{}".format(i),end=" ")
i=i+1
print()
print("="*50)

Example:
---------
#factex1.py
n=int(input("Enter a number:"))
if(n<0):
print("{} is invalid input:".format(n))
else:
# 4 ! = 1 x 2 x 3 x 4 = 24
f=1
i=1
while(i<=n):
f=f*i
i=i+1
else:
print("Factorial={}".format(f))

Example:
--------
#factex2.py
n=int(input("Enter a number:"))
if(n<0):
print("{} is invalid input:".format(n))
else:
# 4 ! = 4 x 3 x 2 x 1 =24
f=1
while(n>0):
f=f*n
n=n-1
else:
print("Factorial={}".format(f))
Example:
-----------------
#forwhileloopex.py
s="PYTHON"
print("By Using while Loop")
i=0
while(i<len(s)):
print(s[i],end=" ")
i=i+1

print("\nBy Using for Loop")


for k in s:
print(k,end=" ")

Example:
----------
#forwhileloopex1.py
lst=[10,"Rossum",2+3j,True,45.67,"Python"]
print("By Using while Loop")
i=0
while(i<len(lst)):
print(lst[i],end=" ")
i=i+1

print("\nBy Using for Loop")


for k in lst:
print(k,end=" ")

Example:
--------------
#forwhileloopex2.py
d1={10:"Python",20:"Data Sci",30:"Java",40:"Oracle",50:"GO"}

k=list(d1.keys())
i=0
while(i<len(k)):
print("{}--->{}".format(k[i],d1[k[i]]))
i=i+1

print("\nBy Using for Loop")


for k,v in d1.items():
print("{}-->{}".format(k,v))

Example:
---------
#Program for accepting list of values and disply them
#ListRead.py
n=int(input("Enter How many values u want in list:")) # n=5
if(n<=0):
print("{} is invalid input:".format(n))
else:
lst=list()
for i in range(1,n+1):
val=float(input("Enter {} value:".format(i)))
lst.append(val)
else:
print("-"*50)
print("List of elements={}".format(lst))
print("-"*50)

Example:
---------------
#Program for accepting list of values and disply them
#ListRead1.py
n=int(input("Enter How many values u want in list:")) # n=5
if(n<=0):
print("{} is invalid input:".format(n))
else:
lst=[] # empty list
print("Enter {} Elements for List:".format(n))
for i in range(1,n+1):
val=float(input())
lst.append(val)
else:
print("-"*50)
print("List of elements={}".format(lst))
print("-"*50)

Example:
----------------
#Program for generating mul table for give +ve number by using for loop
#MulTableFor.py
n=int(input("Enter a number:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
print("="*40)
print("Mul table for {}".format(n))
print("="*40)
for x in range(1,11):
print("\t{} x {} ={}".format(n,x,n*x))
else:
print("="*40)

additional Programs on loops:


Example:
------------
n=int(input("Enter for How many Names u have:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
lst = [] # empty list
print("-" * 50)
print("Enter {} Names".format(n))
print("-" * 50)
for i in range(1, n + 1):
lst.append(input())
else:
print("-" * 50)
print("Original Names:")
print("-" * 50)
for name in lst:
print("\t{}".format(name))
print("-" * 50)
#sort the names in ASCENDING ORDER
lst.sort()
print("Sorted Names in ASCENDING ORDER:")
print("-" * 50)
for name in lst:
print("\t{}".format(name))
print("-" * 50)
# sort the names in DECENDING ORDER
lst.sort(reverse=True)
print("Sorted Names in DECENDING ORDER:")
print("-" * 50)
for name in lst:
print("\t{}".format(name))
print("-" * 50)

Example:
-----------------
#SumAvg.py
n=int(input("Enter for How many values u want to find sum and avg:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
lst=list() # empty list
print("-" * 50)
print("Enter {} Values".format(n))
print("-"*50)
for i in range(1,n+1):
lst.append(float(input()))
else:
print("-" * 50)
print("Content of lst=",lst)
print("Sum=",sum(lst))
print("Average=",sum(lst)/len(lst))
print("-" * 50)

Example:
----------------
#SumAvg.py
n=int(input("Enter for How many values u want to find sum and avg:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
lst=list() # empty list
print("-" * 50)
print("Enter {} Values".format(n))
print("-"*50)
for i in range(1,n+1):
lst.append(float(input()))
else:
print("-" * 50)
print("Content of lst=",lst)
s=0
for val in lst:
s=s+val
else:
print("-" * 50)
print("sum={}".format(s))
print("Average={}".format(s/len(lst)))
print("-" * 50)

Example:
------------------
age=int(input("Enter Age of Citizen:"))
if(age>=18):
print("{} years citizen Eligible to Vote".format(age))
else:
print("{} years citizen not Eligible to Vote".format(age))

Example:
-----------------
while(True):
age=int(input("Enter Age of Citizen:"))
if(age>=18):
break
print("{} years citizen Eligible to Vote".format(age))

Example:
-------------
#Program generating Marks Report
#StudentMarksReport.py
#validation of student number
while(True):
sno=int(input("Enter Student Number(1--100):"))
if(sno>0) and (sno<=100):
break
#accpet the name
sname=input("Enter Student Name:")
#validation of Marks in C
while(True):
cm=int(input("Enter Marks in C:"))
if(cm>=0) and (cm<=100):
break
#validation of Marks in CPPM
while(True):
cppm=int(input("Enter Marks in CPP:"))
if(cppm>=0) and (cppm<=100):
break
#validation of Marks in PYTHON
while(True):
pym=int(input("Enter Marks in PYTHON:"))
if(pym>=0) and (pym<=100):
break
#cal totalmarks and percentage
totmarks=cm+cppm+pym
percent=(totmarks/300)*100
#decide the grade
if(cm<40) or (cppm<40) or (pym<40):
grade="FAIL"
else:
if(totmarks<=300) and (totmarks>=250):
grade="DISTINCTION"
elif(totmarks<=249) and (totmarks>=200):
grade="FIRTST"
elif(totmarks<=199) and (totmarks>=150):
grade="SECOND"
elif(totmarks<=149) and (totmarks>=120):
grade="THIRD"

#display the marks report


print("="*50)
print("\tStudent Marks Report:")
print("="*50)
print("\tStudent Number:{}".format(sno))
print("\tStudent Name:{}".format(sname))
print("\tStudent Marks in C:{}".format(cm))
print("\tStudent Marks in CPP:{}".format(cppm))
print("\tStudent Marks in PYTHON:{}".format(pym))
print("-"*50)
print("\tStudent Total Marks :{}".format(totmarks))
print("\tStudent Percentage of Marks :{}".format(percent))
print("\tStudent Grade :{}".format(grade))
print("="*50)
break statement continue statement Programs:

---------------------------------
break statement
---------------------------------
=>break is a key word
=>The purpose of break statement is that "To terminate the execution of loop logically when certain
condition is satisfied and PVM control comes of corresponding loop and executes other statements in the
program".
=>when break statement takes place inside for loop or while loop then PVM will not execute
corresponding else block of statementys but it always executes other statements in the program.
=>Syntax:
-------------------
for var in Iterable_object:
------------------------------
if (test cond):
break
------------------------------
------------------------------
------------------
=>Syntax:
-------------------
while(Test Cond-1):
------------------------------
if (test cond-2):
break
------------------------------
------------------------------
============================X=================================
-------------------------------------
continue statement
-------------------------------------
=>continue is a keyword
=>continue statement is used for making the PVM to go to the top of the loop without executing the
following statements which are written after continue statement for that current Iteration only.
=>continue statement to be used always inside of loops.
=>when we use continue statement inside of loop then else part of corresponding loop also executes
provided loop condition becomes false.
-----------------
=>Syntax:-
----------------
for varname in Iterable-object:
------------------------------------------
if ( Test Cond):
continue
statement-1 # written after continue statement
statement-2
statement-n
-----------------------------------------
-----------------------------------------

=>Syntax:-
----------------
while (Test Cond):
------------------------------------------
if ( Test Cond):
continue
statement-1 # written after continue stateemnt
statement-2
statement-n
-----------------------------------------
-----------------------------------------

Example:
--------------
#breakex1.py
s="PYTHON"
for ch in s:
if(ch=="H"):
break
else:
print("\t{}".format(ch))

Example:
-----------
#breakex2.py
s="PYTHON"
for ch in s:
if(ch=="O"):
break
else:
print("\t{}".format(ch))
else:
print("i am from for..else block") # Will not execute in the case break stmt in for loop
print("Other statement in Program")

Example:
----------
#breakex3.py
s="PYTHON"
i=0
while(i<len(s)):
if(s[i]=="O"):
break
else:
print(s[i])
i=i+1
else:
print("i am from while..else block") #Will not execute in the case break stmt in while loop
print("Other statement in Program")

Example:
-------------
#program for dciding Prime or not
#primex.py
n=int(input("Enter a Number:")) # n=2
if(n<=1):
print("{} is invalid input:".format(n))
else:
#prime logic
result=True
for i in range(2,n):
if(n%i==0):
result=False
break
if(result==True):
print("{} is PRIME:".format(n))
else:
print("{} is NOT PRIME:".format(n))

Example:
----------
#program for dciding Prime or not
#primex1.py
n=int(input("Enter a Number:")) # n=6
if(n<=1):
print("{} is invalid input:".format(n))
else:
#prime logic
result="PRIME"
for i in range(2,n):
if(n%i==0):
result="NOTPRIME"
break
if(result=="PRIME"):
print("{} is PRIME:".format(n))
else:
print("{} is NOT PRIME:".format(n))

Example:
----------
#program for dciding Prime or not
#primex2.py
n=int(input("Enter a Number:")) # n=9
if(n<=1):
print("{} is invalid input:".format(n))
else:
#prime logic
result="HYD"
for i in range(2,n):
if(n%i==0):
result="BANG"
break
if(result=="HYD"):
print("{} is PRIME:".format(n))
else:
print("{} is NOT PRIME:".format(n))

Example:
----------
#continueex1.py
s="PYTHON"
for ch in s:
if(ch=="H"):
continue
else:
print("\t{}".format(ch))
else:
print("i am from for..else block")
print("Other statement in program")

Example:
-----------
continueex2.py
s="PYTHON"
for ch in s:
if(ch=="Y") or (ch=="O"):
continue
print("\t{}".format(ch))
else:
print("i am from for..else block")
print("Other statement in program")

Example:
---------
#continueex3.py
s="PYTHON"
for ch in s:
if ch in ["Y","T","H"]:
continue
print("\t{}".format(ch))
else:
print("i am from for..else block")
print("Other statement in program")

Example:
---------
#continueex4.py
lst=[10,"Rossum",23.45,3+4j,True]
for val in lst:
if(val not in ["Rossum",23.45]):
continue
print("\t{}".format(val))

Example:
-----------
#continueex4.py
lst=[10,"Rossum",23.45,3+4j,True]
i=0
while(i<len(lst)):
if(lst[i] in [23.45,3+4j,True]):
i=i+1
continue
print("\t{}".format(lst[i]))
i=i+1

Example:
----------
#continueex6.py
n=int(input("Enter How many numnbers u want:"))
if(n<=0):
print("{} is invalid:".format(n))
else:
lst=list()
print("Enter {} Values:".format(n))
for i in range(1,n+1):
lst.append(float(input()))
else:
print("Given List={}".format(lst)) # Given List=[12.0, -34.0, -12.34, 45.0]
#logic for obtaining +ve numbers
print("Possitive Numbers:")
for val in lst:
if(val<0):
continue
print("\t{}".format(val),end=" ")

else:
print()
print("Negative Numbers:")
for val in lst:
if(val>0):
continue
print("\t{}".format(val),end=" ")

Example:
-----------

#continueex7.py
n=int(input("Enter How many numnbers u want:"))
if(n<=0):
print("{} is invalid:".format(n))
else:
lst=list()
print("Enter {} Values:".format(n))
for i in range(1,n+1):
lst.append(float(input()))
else:
#logic for obtaining +ve numbers
pslist=list()
for val in lst:
if(val<=0):
continue
pslist.append(val)
else:
#logic for obtaining +ve numbers
nlist=list()
print("Negative Numbers:")
for val in lst:
if(val>=0):
continue
nlist.append(val)
else:
print("-"*50)
print("Given List:{}".format(lst))
print("Posstive Nums List:{}".format(pslist))
print("Negative Nums List:{}".format(nlist))
print("-"*50)

Inner loops concept programs:

Example:
-------------
#forwhileloopex1.py
lst=[10,"Rossum",2+3j,True,45.67,"Python"]
print("By Using while Loop")
i=0
while(i<len(lst)):
print(lst[i],end=" ")
i=i+1

print("\nBy Using for Loop")


for k in lst:
print(k,end=" ")

#forwhileloopex2.py
d1={10:"Python",20:"Data Sci",30:"Java",40:"Oracle",50:"GO"}

k=list(d1.keys())
i=0
while(i<len(k)):
print("{}--->{}".format(k[i],d1[k[i]]))
i=i+1

print("\nBy Using for Loop")


for k,v in d1.items():
print("{}-->{}".format(k,v))

Example:
--------------
#InnerLoopEx1.py (for loop inside for loop)
for i in range(1,5): #outer for loop
print("-"*50)
print("Val of i--outer for loop=",i)
print("-"*50)
for j in range(1,4):# inner for loop
print("\tVal of j--inner for loop=",j)
else:
print("Out-of inner for loop")
print("-"*50)
else:
print("Out-of outer for loop")
print("-"*50)

"""
E:\KVR-PYTHON-9AM\LOOPS>py InnerLoopEx1.py
--------------------------------------------------
Val of i--outer for loop= 1
--------------------------------------------------
Val of j--inner for loop= 1
Val of j--inner for loop= 2
Val of j--inner for loop= 3
Out-of inner for loop
--------------------------------------------------
--------------------------------------------------
Val of i--outer for loop= 2
--------------------------------------------------
Val of j--inner for loop= 1
Val of j--inner for loop= 2
Val of j--inner for loop= 3
Out-of inner for loop
--------------------------------------------------
--------------------------------------------------
Val of i--outer for loop= 3
--------------------------------------------------
Val of j--inner for loop= 1
Val of j--inner for loop= 2
Val of j--inner for loop= 3
Out-of inner for loop
--------------------------------------------------
--------------------------------------------------
Val of i--outer for loop= 4
--------------------------------------------------
Val of j--inner for loop= 1
Val of j--inner for loop= 2
Val of j--inner for loop= 3
Out-of inner for loop
--------------------------------------------------
Out-of outer for loop
--------------------------------------------------
"""

Example:
---------------
#InnerLoopEx2.py (while loop inside while loop)
i=1
while(i<=5): #outer while loop
print("-"*50)
print("Val of i--outer while loop=",i)
print("-"*50)
j=1
while(j<=3):# inner for loop
print("\tVal of j--inner while loop=",j)
j=j+1
else:
i=i+1
print("Out-of inner while loop")
print("-"*50)
else:
print("Out-of outer while loop")
print("-"*50)

"""
E:\KVR-PYTHON-9AM\LOOPS>py InnerLoopEx2.py
--------------------------------------------------
Val of i--outer while loop= 1
--------------------------------------------------
Val of j--inner while loop= 1
Val of j--inner while loop= 2
Val of j--inner while loop= 3
Out-of inner while loop
--------------------------------------------------
--------------------------------------------------
Val of i--outer while loop= 2
--------------------------------------------------
Val of j--inner while loop= 1
Val of j--inner while loop= 2
Val of j--inner while loop= 3
Out-of inner while loop
--------------------------------------------------
--------------------------------------------------
Val of i--outer while loop= 3
--------------------------------------------------
Val of j--inner while loop= 1
Val of j--inner while loop= 2
Val of j--inner while loop= 3
Out-of inner while loop
--------------------------------------------------
--------------------------------------------------
Val of i--outer while loop= 4
--------------------------------------------------
Val of j--inner while loop= 1
Val of j--inner while loop= 2
Val of j--inner while loop= 3
Out-of inner while loop
--------------------------------------------------
--------------------------------------------------
Val of i--outer while loop= 5
--------------------------------------------------
Val of j--inner while loop= 1
Val of j--inner while loop= 2
Val of j--inner while loop= 3
Out-of inner while loop
--------------------------------------------------
Out-of outer while loop
--------------------------------------------------"""
Example:
------------------
#InnerLoopEx3.py (while loop inside for loop)
for i in range(5,0,-1): #outer for loop
print("-"*50)
print("Val of i--outer for loop=",i)
print("-"*50)
j=3
while(j>=1):# inner while loop
print("\tVal of j--inner while loop=",j)
j=j-1
else:
print("Out-of inner while loop")
print("-"*50)
else:
print("Out-of outer for loop")
print("-"*50)

"""
E:\KVR-PYTHON-9AM\LOOPS>py InnerLoopEx3.py
--------------------------------------------------
Val of i--outer for loop= 5
--------------------------------------------------
Val of j--inner while loop= 3
Val of j--inner while loop= 2
Val of j--inner while loop= 1
Out-of inner while loop
--------------------------------------------------
--------------------------------------------------
Val of i--outer for loop= 4
--------------------------------------------------
Val of j--inner while loop= 3
Val of j--inner while loop= 2
Val of j--inner while loop= 1
Out-of inner while loop
--------------------------------------------------
--------------------------------------------------
Val of i--outer for loop= 3
--------------------------------------------------
Val of j--inner while loop= 3
Val of j--inner while loop= 2
Val of j--inner while loop= 1
Out-of inner while loop
--------------------------------------------------
--------------------------------------------------
Val of i--outer for loop= 2
--------------------------------------------------
Val of j--inner while loop= 3
Val of j--inner while loop= 2
Val of j--inner while loop= 1
Out-of inner while loop
--------------------------------------------------
--------------------------------------------------
Val of i--outer for loop= 1
--------------------------------------------------
Val of j--inner while loop= 3
Val of j--inner while loop= 2
Val of j--inner while loop= 1
Out-of inner while loop
--------------------------------------------------
Out-of outer for loop
--------------------------------------------------
"""
Example:
--------------------
#InnerLoopEx4.py (for loop inside while loop)
i=1
while(i<=5): #outer while loop
print("-"*50)
print("Val of i--outer while loop=",i)
print("-"*50)
for j in range(3,0,-1):# inner for loop
print("\tVal of j--inner for loop=",j)
else:
i=i+1
print("Out-of inner for loop")
print("-"*50)
else:
print("Out-of outer while loop")
print("-"*50)
"""
E:\KVR-PYTHON-9AM\LOOPS>py InnerLoopEx4.py
--------------------------------------------------
Val of i--outer while loop= 1
--------------------------------------------------
Val of j--inner for loop= 3
Val of j--inner for loop= 2
Val of j--inner for loop= 1
Out-of inner for loop
--------------------------------------------------
--------------------------------------------------
Val of i--outer while loop= 2
--------------------------------------------------
Val of j--inner for loop= 3
Val of j--inner for loop= 2
Val of j--inner for loop= 1
Out-of inner for loop
--------------------------------------------------
--------------------------------------------------
Val of i--outer while loop= 3
--------------------------------------------------
Val of j--inner for loop= 3
Val of j--inner for loop= 2
Val of j--inner for loop= 1
Out-of inner for loop
--------------------------------------------------
--------------------------------------------------
Val of i--outer while loop= 4
--------------------------------------------------
Val of j--inner for loop= 3
Val of j--inner for loop= 2
Val of j--inner for loop= 1
Out-of inner for loop
--------------------------------------------------
--------------------------------------------------
Val of i--outer while loop= 5
--------------------------------------------------
Val of j--inner for loop= 3
Val of j--inner for loop= 2
Val of j--inner for loop= 1
Out-of inner for loop
--------------------------------------------------
Out-of outer while loop
--------------------------------------------------
"""
Example:
-------------
#Multables.py
n=int(input("Enter How Many Mul Tables u want:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
for i in range(1,n+1):
print("-"*50)
print("Mul Table for:{}".format(i))
print("-"*50)
for j in range(1,11):
print("\t{} x {} = {}".format(i,j,i*j))
else:
print("-"*50)
else:
print("-"*50)
Example:
--------------
#primelist.py
n=int(input("Enter a Number for extracting prime numbers:"))
if(n<=0):
print("{} invalid input:".format(n))
else:
lst=list()
for i in range(1,n+1):
n=int(input("Enter {} number :".format(i)))
lst.append(n)
else:
print("-"*50)
print("Given List of Elements:",lst) #[5,2,15,9,-4,0,1,23]
print("-"*50)
pnl=[]
for n in lst:
if(n<=1):pass
else:
result=True
for i in range(2,n):
if(n%i==0):
result=False
break
if(result):
pnl.append(n)
else:
print("List of Prime Number in {}={}".format(lst,pnl))
==================================================
Inner or nested loops
==================================================
=>The process of defining one loop inside of another loop is called inner or nested loop.
=>The execution process of inner or nested loop is that "For Every Value outer loop , inner
loops executes for finite number of times until its condition becomes False".
=>We can different ways of inner loop and they are given with the following syntaxes.

=>Syntax1: ( For loop inside of For loop)


------------------------
for varname1 in Iterable_object1: # Outer For loop
----------------------------------
for varname2 in Iterable_object2: #Inner For
Loop
----------------------------------
else:
--------------------------
else:
----------------------------------------

------------------------
=>Syntax2: ( While loop inside of While loop)
------------------------
----------------------------------------
while(Test Cond1): # Outer while loop
-------------------------------
while(Test Cond2): # Inner while loop
----------------------
----------------------
else:
-------------------------
else:
--------------------------------
---------------------------------

------------------------
=>Syntax3: (While loop inside of for loop
------------------------
for varname1 in Iterable_object1: # Outer For loop
----------------------------------
while(Test Cond2): # Inner while loop
----------------------
----------------------
else:
-------------------------
else:
----------------------------------------

------------------------
=>Syntax4: (For loop Inside of while loop )
------------------------
----------------------------------------
while(Test Cond1): # Outer while loop
-------------------------------
for varname2 in Iterable_object2: #Inner For Loop
----------------------------------
else:
--------------------------
else:
--------------------------------
---------------------------------

=====================================================================

=====================================================
Functions in Python
=====================================================
Index
---------------------------------
=>Purpose of Functions
=>Types of Types of Languages
a) Un-Structured Programming Lang
b) Structured Programming Lang
=>Definition of Function
=>Parts of Functions
=>Phases in Functions
=>Syntax for Defining Functions in Python
=>Programming Examples
-----------------------------------------------------------------------------------------------------
=>Arguments and parameters
=>Types of Arguments / Parameters
a) Possitional Arguments
b) Default Arguments
c) Keyword Arguments
d) Variable Length Arguments
e) Keyword Variable Length Arguments
=>Programming Examples
-----------------------------------------------------------------------------------------------------
=>Global Variables and Local variables
=>global keyword and globals()
=>Programming Examples
=>Anonymous Functions OR Lambda Functions
=>Programming Examples
------------------------------------------------------------------------------------------------------
=>Special Functions in Python
a) filter() with Normal Function and Anonymous Functions
b) map() with Normal Function and Anonymous Functions
c) reduce() with Normal Function and Anonymous Functions
=>Programming Examples
=============================x======================================

=====================================================
Types of Languages in the context of Functions
=====================================================
=>In the context of Functions, we have two types of languages. They are
a) Un-Structured Programming Lang
b) Structured Programming Lang
---------------------------------------------------------------
a) Un-Structured Programming Lang
---------------------------------------------------------------
=>In These Programming Languages, we don't have the concept of Functions.
=>Since Un-Structured Programming Languages does not contain the concept of Functions, so that they
the following Limitations.
1. Application Development time is More
2. Application Memory Space is More
3. Application Execution time is More (slow)
4. Application Performance is degraded
5. Redundency (Duplication or replication) of the code is more.
=>Example: GW-BASIC
=================================================================
b) Structured Programming Languages
---------------------------------------------------------------
=>In These Programming Languages, we have the concept of Functions.
=>Since Structured Programming Languages contains the concept of Functions, so that they the following
Advantages.
1. Application Development time is Less
2. Application Memory Space is Less
3. Application Execution time is Less (fast)
4. Application Performance is enhanced(Improved)
5. Redundency (Duplication or replication) of the code is Minimized.

Examples: C, CPP, JAVA, .NET, PYTHON...etc


=============================================================

=====================================================
Functions in Python
=====================================================
=>Purpose of Functions is that " To Perform Certain Operation and Provdes Code
Re-Usability".
-----------------------------------------
=>Definition of Function:
-----------------------------------------
=>Sub Program of Main Program is called Function
(OR)
=>A part of main program is called Function.
---------------------------------------------------------------------------------------------------------
Parts of Functions
---------------------------------------------------------------------------------------------------------
=>When we define a function, we must ensure there must exist 2 parts. They are
1) Function Definition
2) Function Call.
=>For Every Function Call , there must exist Function Definition otherwise we get NameError.
=> Function Definition will execute by calling though the function call otherwise Function
Definition will not execute.
=>The Perticular Function Definition will exist one time where we can have multiple Function
calls for one function Definition
--------------------------------------------------------------------------------------------------------------

Programs on Functions ( Approaches):

Example:
------------
#Program for computing sum of two numbers by using Functions
#Approach1.py
#INPUT: From Function Calls
#PROCESS: Inside of Function Body
#RESULT: To Function Call
def sumop(a,b): # Here 'a' and 'b' are called formal parameters
c=a+b # here 'c' is called Local Variable
return c

#main program
print("type of sumop=",type(sumop))
x=float(input("Enter First Value:"))
y=float(input("Enter Second Value:"))
kvr=sumop(x,y) # Function Call
print("sum=",kvr)

Example:
-------------
#Program for computing sum of two numbers by using Functions
#Approach2.py
#INPUT: Inside of Function Body
#PROCESS: Inside of Function Body
#RESULT: Inside of Function Body

def sumop():
#Taking INPUT
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
#Process
c=a+b
#Gives Result
print("sum({},{})={}".format(a,b,c))

#main program
print("type of sumop=",type(sumop))
sumop()
Example:
---------------
#Program for computing sum of two numbers by using Functions
#Approach3.py
#INPUT: Inside of Function Body
#PROCESS: Inside of Function Body
#RESULT: To Function Call
def sumop():
#Taking INPUT
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
#PROCESS
c=a+b
#gives RESULT to Function Call
return c

#main program
result=sumop()
print("Sum={}".format(result))

Example:
------------
#Program for computing sum of two numbers by using Functions
#Approach3Copy.py
#INPUT: Inside of Function Body
#PROCESS: Inside of Function Body
#RESULT: To Function Call
def sumop():
#Taking INPUT
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
#PROCESS
c=a+b
#gives RESULT to Function Call
return a,b,c # In Python Programming, a return statement can return one or more number of
values

#main program
k,v,r=sumop() # Multi line assigment with Function Call
print("Sum({},{})={}".format(k,v,r))
print("----------------------OR----------------------------")
res=sumop() # Here res is an object of <class, tuple>
print("sum({},{})={}".format(res[0],res[1],res[2]))

Example:
------------
#Program for computing sum of two numbers by using Functions
#Approach4.py
#INPUT: From Function Call
#PROCESS: Inside of Function Body
#RESULT: Inside of Function Body
def sumop(k,v):
r=k+v
print("sum({},{})={}".format(k,v,r))

#main program
a=float(input("Enter First Value:"))
b=float(input("Enter First Value:"))
sumop(a,b) # Function Call

Example:
---------------
#listmaxmin.py
def readvalues():
n=int(input("Enter How Many Number Values u have:"))
if(n<=0):
return list()
else:
lst=[]
print("-"*50)
print("Enter {} Values:".format(n))
print("-"*50)
for i in range(1,n+1):
lst.append(float(input()))
return lst

def findmax(kvr):
return (max(kvr))

def findmin(hyd):
return (min(hyd))
#main program
res=readvalues()
if(len(res)==0):
print("List is Empty")
else:
maxv=findmax(res)
minv=findmin(res)
print("max({})={}".format(res,maxv))
print("min({})={}".format(res,minv))

Example:
--------------
#Program for swapping of two values by using Functions
#SwapEx1.py
def swap(a,b):
a,b=b,a
return a,b

#main program
a=input("Enter Value of a:")
b=input("Enter Value of b:")
print("-"*50)
print("Original Value of a:",a)
print("Original Value of b:",b)
res=swap(a,b)
print("-"*50)
print("Swapped Value of a:",res[0])
print("Swapped Value of b:",res[1])

Example:
------------
#Program for swapping of two values by using Functions
#SwapEx2.py
def swap(a,b):
a=a^b
b=a^b
a=a^b
return a,b

#main program
a=int(input("Enter Value of a:"))
b=int(input("Enter Value of b:"))
print("-"*50)
print("Original Value of a:",a)
print("Original Value of b:",b)
res=swap(a,b)
print("-"*50)
print("Swapped Value of a:",res[0])
print("Swapped Value of b:",res[1])

Example:
------------
#Program for swapping of two values by using Functions
#SwapEx3.py
def swap():
a=int(input("Enter Value of a:"))
b=int(input("Enter Value of b:"))
print("-"*50)
print("Original Value of a:",a)
print("Original Value of b:",b)
a=a^b
b=a^b
a=a^b
return a,b

#main program
res=swap()
print("-"*50)
print("Swapped Value of a:",res[0])
print("Swapped Value of b:",res[1])

Parameters and arguments Types of arguments Positional Arguments Default Arguments Programs
---------------------------------------------------------------------------------------------
=============================================
Types of Arguments or Parameters
=============================================
=>Based on the values of arguments from function call passing to the parameters of the function definition,
the arguments are classified into 5 types. They are
1. Possitonal Arguments
2. Default Arguments
3. Key Arguments
4. Variable Length Arguments
5. Key Word Variable Length Arguments

============================================
1. Possitional Arguments
============================================
=>It is one the default arguments passing mechanism.
=>The concept of Possitonal Arguments is that Number of arguments in Function call must be equal to Number
of Formal Parameters in Function Definition.
=>The concept of Possitonal Arguments also recommends to maintain order and meaning for higher accuracy
for Data .
=>Possitonal Arguments passing mechanism given by PVM as First Priority.
----------------------------------------------------------
=>Syntax for Function Definition
---------------------------------------------------------

def functionname(param1,param2,...param-n):
--------------------------------------------
Block of statement---Processing Logic
--------------------------------------------

=>Syntax for Function Call:


---------------------------------------------
functionname(arg1,arg2,....arg-n)
=>Here the values of arg1,arg2,....arg-n are passsing param1, param2....param-n respectively.

======================================
2) Default Parameters (or) arguments
============================================
=>When there is a Common Value for family of Function Calls then Such type of Common Value(s) must
be taken as default parameter with common value (But not recommended to pass by using Posstional
Parameters)

Syntax: for Function Definition with Default Parameters


----------------------------------------------------------------------------------------
def functionname(param1,param2,....param-n-1=Val1, Param-n=Val2):
------------------------------------------------------------------
------------------------------------------------------------------

Here param-n-1 and param-n are called "default Parameters"


and param1,param-2... are called "Possitional parameters"

Rule-: When we use default parameters in the function definition, They must be used as last Parameter(s)
otherwise we get Error( SyntaxError: non-default argument (Possitional ) follows default argument).

================================================
Arguments and parameters
================================================
--------------------
Parameters
----------------------
=>Parameters are the Varaibles used in Function Heading and they are also called Formal
Parameters.
=>The purpose of formal Parameter is that To store the inputs coming from function calls.
----------------------
Arguments:
----------------------
=>Arguments(Actual Arguments) are also called Variables used in Function Calls.
=>The Relation between Arguments and parameters is that All the values of Arguments are
passing to Formal Parameters.
=>The data passed from Function Calls to Function definition in the form arguments or Argument values
from Function calls to Function Definition in the form Formal Parameters.

Example:
------------
#ParamsArgsEx1.py
def disp(x,y,z): # Function Definition---here 'x' 'y' and 'z' are called Formal Params
print("\nx={},y={}, z={}".format(x,y,z))

#main program
a=10
b=20
c=30
disp(a,b,c) # Function Call--here 'a' 'b' and 'c' are called arguments
disp(600,700,800) # Function Call--here 600, 700 800 are called argument values

Example:
----------
#Program for demnostaring Possitioanl Arguments
#PossArgsEx1.py
def dispstudinfo(sno,sname,marks):
print("\t{}\t{}\t{}".format(sno,sname,marks))

#main program
print("-"*50)
print("\tSno\tName\tMarks")
print("-"*50)
dispstudinfo(10,"RS",33.44) # Function Call
dispstudinfo(20,"DR",63.44) # Function Call
dispstudinfo(30,"TR",13.44) # Function Call
dispstudinfo("MC",34.56,56) # Function Call---recomended to maintain order and meaning.

print("-"*50)

Example:
-----------
#Program for demnostaring Default Arguments
#DefaultArgsEx2.py
def dispstudinfo(sno,sname,marks,crs="PYTHON"):
print("\t{}\t{}\t{}\t{}".format(sno,sname,marks,crs))

#main program
print("-"*50)
print("\tSno\tName\tMarks\tCourse")
print("-"*50)
dispstudinfo(10,"RS",33.44) # Function Call
dispstudinfo(20,"DR",63.44) # Function Call
dispstudinfo(30,"TR",13.44) # Function Call
dispstudinfo(34,"MC",56.56) # Function Call
dispstudinfo(40,"MD",26.66,"JAVA")
dispstudinfo(50,"SR",36.66)
print("-"*50)
Example:
------------
#Program for demnostaring Default Arguments
#DefaultArgsEx3.py
def dispstudinfo(sno,sname,marks,crs="PYTHON",cnt="INDIA"):
print("\t{}\t{}\t{}\t{}\t{}".format(sno,sname,marks,crs,cnt))

#main program
print("-"*50)
print("\tSno\tName\tMarks\tCourse\tCountry")
print("-"*50)
dispstudinfo(10,"RS",33.44) # Function Call
dispstudinfo(20,"DR",63.44) # Function Call
dispstudinfo(30,"TR",13.44) # Function Call
dispstudinfo(34,"MC",56.56) # Function Call
dispstudinfo(40,"MD",26.66,"JAVA")
dispstudinfo(50,"SR",36.66)
dispstudinfo(60,"TR",16.66,"PHP","USA")
print("-"*50)

Example:
-----------
#Program for demnostaring Default Arguments
#DefaultArgsEx4.py
def dispstudinfo1(sno,sname,marks,crs="PYTHON",cnt="INDIA"):
print("\t{}\t{}\t{}\t{}\t{}".format(sno,sname,marks,crs,cnt))

def dispstudinfo2(sno,sname,marks,crs="JAVA",cnt="INDIA"):
print("\t{}\t{}\t{}\t{}\t{}".format(sno,sname,marks,crs,cnt))
#main program
print("-"*50)
print("\tSno\tName\tMarks\tCourse\tCountry")
print("-"*50)
dispstudinfo1(10,"RS",33.44) # Function Call
dispstudinfo1(20,"DR",63.44) # Function Call
dispstudinfo1(30,"TR",13.44) # Function Call
dispstudinfo1(34,"MC",56.56) # Function Call
print("-"*50)
print("\tSno\tName\tMarks\tCourse\tCountry")
print("-"*50)
dispstudinfo2(40,"MD",26.66)
dispstudinfo2(50,"SR",36.66)
dispstudinfo2(60,"TR",16.66)
print("-"*50)

Example:
---------
#DefaultArgsEx5.py
def area(r,PI=3.14):
ar=PI*r**2
print("Area of Circle={}".format(ar))

def peri(r,PI=3.14):
pr=2*PI*r
print("Perimeter of Circle={}".format(pr))
#main program
r=float(input("Enter Radious for area Cal:"))
area(r)
print("==============================")
r=float(input("Enter Radious for Perimeter Cal:"))
peri(r)

----------------------------------------------
Keyword Parameters (or) arguments Programs:
--------------------------------------------------------------------------
Example:
---------
#Program for demonstarting Keyword arguments
#KwdArgsEx1.py------------a=10 b= 20 c=30 d=40
def disp(a,b,c,d):
print("\t{}\t{}\t{}\t{}".format(a,b,c,d))

#main program
print("-"*50)
print("\ta\tb\tc\td")
print("-"*50)
disp(10,20,30,40) # Functional Call---Poss Args only
disp(d=40,c=30,a=10,b=20) # Functional Call- kwd args only
disp(c=30,a=10,d=40,b=20) # Functional Call- kwd args only
disp(10,20,d=40,c=30) # Functional Call- Poss args and kwd args
#disp(d=40,c=30,10,20) ---SyntaxError: positional argument follows keyword argument
disp(10,d=40,b=20,c=30) #Functional Call- Poss args and kwd args
print("-"*50)

Example:
---------------
#Program for demonstarting Keyword arguments
#KwdArgsEx2.py
def dispempinfo(eno,ename,sal,dsg,cname="IBM",sub="PYTHON"):
print("\t{}\t{}\t{}\t{}\t{}\t{}".format(eno,ename,sal,dsg,cname,sub))

#main program
print("="*70)
print("\tEno\tName\tSal\tDesg\tCname\tSubject")
print("="*70)
dispempinfo(10,"RS",4.5,"Author") # Function Call Poss Args.
dispempinfo(20,"HJ",3.5,"SE",sub="DS") # Function Call Poss Args with Kwd args
dispempinfo(cname="TCS",eno=30,ename="SR",dsg="TR",sal=1.3)
#dispempinfo(40,"MN",dsg="TL",cname="HCL",3.4,"Django")---SyntaxError: positional argument follows
keyword argument
dispempinfo(40,"MN",sub="Django",dsg="TL",cname="HCL",sal=3.4)
print("="*70)

============================================
3) Keyword Parameters (or) arguments
============================================
=>In some of the circumstances, we know the function name and formal parameter names and we don't
know the order of formal Parameter names and to pass the data / values accurately we must use the concept
of Keyword Parameters (or) arguments.
=>The implementation of Keyword Parameters (or) arguments says that all the formal parameter names
used as arguments in Function call(s) as keys.

Syntax for function definition:-


-------------------------------------------------
def functionname(param1,param2...param-n):
---------------------------------------------
---------------------------------------------

Syntax for function call:-


-------------------------------------------------
functionname(param-n=val-n,param1=val1,param-n-1=val-n-1,......)

Here param-n=val-n,param1=val1,param-n-1=val-n-1,...... are called Keywords arguments

Variables Length Parameters (or) arguments Programs:

================================================
4) Variables Length Parameters (or) arguments
================================================
=>When we have familiy of multiple function calls with Variable number of values / arguments then with
normal python programming, we must define mutiple function defintions. This process leads to more
development time. To overcome this process, we must use the concept of Variable length Parameters .
=>To Impelement, Variable length Parameters concept, we must define single Function Definition and
takes a formal Parameter preceded with a symbol called astrisk ( * param) and the formal parameter with
astrisk symbol is called Variable length Parameters and whose purpose is to hold / store any number of
values coming from similar function calls and whose type is <class, 'tuple'>.
------------------------------------------------------------------------------------------------------
Syntax for function definition with Variables Length Parameters:
------------------------------------------------------------------------------------------------------
def functionname(list of formal params, *param1,param2=value) :
--------------------------------------------------
--------------------------------------------------

=>Here *param1 is called Variable Length parameter and it can hold any number of argument values (or)
variable number of argument values and *param1 type is <class,'tuple'>

=>Rule:- The *param must always written at last part of Function Heading and it must be only one (but not
multiple)

=>Rule:- When we use Variable length and default parameters in function Heading, we use default
parameter as last and before we use variable length parameter and in function calls, we should not use
default parameter as Key word argument bcoz Variable number of values are treated as Posstional
Argument Value(s)

------------------------------------
Examples:
------------------------------------
#Program for demnstrating Variable Length Arguments
#VarArgsEx1.py---------------This program will not execute as it is
def disp(a):
print("{}".format(a))
def disp(a,b):
print(a,b)

def disp(a,b,c):
print(a,b,c)

def disp(a,b,c,d):
print(a,b,c,d)

#main program
disp(10) # Funcrtion call
disp(10,20) # Funcrtion call
disp(10,20,30) # Funcrtion call
disp(10,20,30,40) # Funcrtion call
------------------------------------
Examples:
------------------------------------
#Program for demnstrating Variable Length Arguments
#VarArgsEx2.py---------------This program will execute as it is
def disp(a):
print("{}".format(a))

disp(10) # Function call

def disp(a,b):
print(a,b)

disp(10,20) # Function call

def disp(a,b,c):
print(a,b,c)

disp(10,20,30) # Function call

def disp(a,b,c,d):
print(a,b,c,d)

disp(10,20,30,40) # Function call


------------------------------------
Examples:
------------------------------------
#Program for demonstrating Variable Length Arguments
#PureVarArgsEx1.py
def disp( *k):
print("-"*50)
for val in k:
print("{}".format(val), end="\t")
print()
print("-"*50)

#main program
disp(10) # Funcrtion call
disp(10,20) # Funcrtion call
disp(10,20,30) # Funcrtion call
disp(10,20,30,40) # Funcrtion call
disp("Pyt","DSC","DAJ","Java","R")
disp()
------------------------------------
Examples:
------------------------------------
#Program for demonstrating Variable Length Arguments
#PureVarArgsEx2.py
def disp( *k,city="HYD"):
print("-"*50)
print("City=",city)
for val in k:
print("{}".format(val), end="\t")
print()
print("-"*50)

#main program
disp(10) # Funcrtion call
disp(10,20) # Funcrtion call
disp(10,20,30) # Funcrtion call
disp(10,20,30,40) # Funcrtion call
disp("Pyt","DSC","DAJ","Java","R")
disp()
disp(city="Bang")
disp(40,50,60,70,80,90,city="MUM")

------------------------------------
Examples:
------------------------------------
#Program for demonstrating Variable Length Arguments
#PureVarArgsEx3.py
def disp(sname, *k,city="HYD"):
print("-"*50)
print("{} Lives in {} City".format(sname,city))
for val in k:
print("{}".format(val), end="\t")
print()
print("-"*50)

#main program
disp("Rohit",10) # Funcrtion call
disp("Ramesh",10,20) # Funcrtion call
disp("Kaif",10,20,30) # Funcrtion call
disp("Surya",10,20,30,40) # Funcrtion call
disp("Binaya","Pyt","DSC","DAJ","Java","R")
disp(city="MUM",sname="Uday")
disp("Naveed",city="Bang")
disp("Pradip",40,50,60,70,80,90,city="MUM")
#disp("Vamshi",city="MUM",40,50,60,70,80,90) SyntaxError: positional argument follows keyword
argument
disp("Vamshi",40,50,60,70,80,90,city="MUM")

------------------------------------
Examples:
------------------------------------
#Program for demonstrating Variable Length Arguments
#PureVarArgsEx4.py
def findsum(sname,*n,s=0):
print("-"*50)
print("Given Numbers supplied by {}:".format(sname))
for val in n:
print("{}".format(val),end="\t")
s=s+val
print()
if(len(n)!=0):
print("Sum=",s)
print("Avg=%0.2f" %(s/len(n)))
else:
print("Sum=",s)
print("Avg=0")

print("-"*50)

#main program
findsum("Rossum",10,20,30,40,50,60)
findsum("Ritche",10,20,30,40)
findsum("Rajan",50,60)
findsum("KVR",-10,-20,-30,40,50,60,-70)
findsum("Rohit")

Key Word Variables Length Parameters (or) arguments:


=======================================================
5) Key Word Variables Length Parameters (or) arguments
=======================================================
=>When we have familiy of multiple function calls with Key Word Variable number of values / arguments then
with normal python programming, we must define mutiple function defintions. This process leads to more
development time. To overcome this process, we must use the concept of Keyword Variable length Parameters .
=>To Implement, Keyword Variable length Parameters concept, we must define single Function Definition and
takes a formal Parameter preceded with a symbol called double astrisk ( ** param) and the formal
parameter with double astrisk symbol is called Keyword Variable length Parameters and whose purpose is to
hold / store any number of (Key,Value) coming from similar function calls and whose type is <class, 'dict'>.
---------------------------------------------------------------------------
Syntax for function definition with Keyword Variables Length Parameters:
---------------------------------------------------------------------------
def functionname(list of formal params, **param) :
--------------------------------------------------
--------------------------------------------------

=>Here **param is called Keyword Variable Length parameter and it can hold any number of Key word
argument values (or) Keyword variable number of argument values and **param type is <class,'dict'>

=>Rule:- The **param must always written at last part of Function Heading and it must be only one (but not
multiple)

---------------------
Final Syntax:
---------------------------
def funcname(PosFormal parms, *Varlenparams, default params, **kwdvarlenparams):
-------------------------------------------------
---------------------------------------------------

------------------------------------
Examples:
------------------------------------
#Program for demonstrating Key Word Variable Length Arguments-
#PureKwdVarArgsEx1.py----This program will not execute as it is
def dispvalues(**a):
print("-"*40)
for k,v in a.items():
print("\t{}-->{}".format(k,v))
print("-"*40)

#main program
dispvalues(a=10,b=20,c=30,d=40) # Function Call1
dispvalues(x=100,y=200,z=300) # Function Call2
dispvalues(k=1,v=2,r=3,n=4,I=5) # Function Call3
dispvalues(p=10,q=20)
dispvalues(r=20)
dispvalues()

------------------------------------
Examples:
------------------------------------
#PureKwdVarArgsEx2.py
def findtotal(sname,cls,**submarks):
print("-"*50)
totmarks=0
print("Student Name:{}".format(sname))
print("Student Class:{}".format(cls))
print("\tSubjects\tMarks")
for k,v in submarks.items():
print("\t{}\t\t{}".format(k,v))
totmarks=totmarks+v
print("-"*50)
print("\tTotal Marks:",totmarks)
print("-"*50)

#main program
findtotal("Suraj","X",Hindi=90,Eng=78,Maths=80,Sci=78,Soc=79)
findtotal("Akram","XII",Mathematics=74,Physics=55,Chemstry=54)
findtotal("Satish","B.Tech(CSE)",C=50,CPP=60)
findtotal("Aditya","MS",AI=60)
findtotal("Rossum","Scientist")
findtotal("Redy","X",Telugu=80,Eng=58,Maths=89,Sci=58,Soc=69)

------------------------------------
Examples:
------------------------------------
#Program demonstarting Keyword Variable Length Arguments (or) Parameters
#purekwdvarlenargex3.py---This Program will execute

def showinfo(SSID,crs="PYTHON",**n):
print("-"*50)
print("Type of n={} and Number of elements ={}".format(type(n),len(n)))
print("Social Security Id={}".format(SSID))
print("Course Name={}".format(crs))
print("-"*50)
for x,y in n.items():
print("\t{}--->{}".format(x,y))
else:
print("-"*50)
#main program
showinfo(111,sno=10,sname="Ram",M1=40,M2=50,M3=60) # Function Call-1
showinfo(222,eno=20,ename="Raj",sal=6.7,dsg="SE") # Function Call-2
showinfo(333,tno=40,tname="Rakesh",subject="Python") # Function Call-3
showinfo(444,cno=50,cname="Naresh")
showinfo(555,name="Agarwal")
showinfo(666)
showinfo(777,"JAVA",sename="Goutham")

------------------------------------
Examples:
------------------------------------
#purekwdvarlenargsex4.py
def disp(no,sname,*n,city="HYD",**hyd):
print("="*50)
print("\tNumber={}".format(no))
print("\tName={}".format(sname))
print("\tLiving City={}".format(city))
print("Variable Argument Values:")
for v in n:
print("\t{}".format(v))
print("Keyword Variable Argument Values:")
for k,v in hyd.items():
print("\t{}-->{}".format(k,v))
print("="*50)

#main program
disp(1,"RS",10,20,30,a=100,b=200)
disp(2,"TR",50,60,x=1,y=2,z=3)
disp(3,"MC",10,20,30,40,p=-1,q=-2,r=-3,k=-4)
disp(4,"KV",200,300,400,city="AP",K=10,V=20)
disp(45,"Ram",10,20,30,L=70,M=80,city="bang")

Global variables and Local Variables programs:

===========================================
Global variables and Local Variables
===========================================
=>Local Variables are those which are defined / used Inside of Function Body.
=>Local Variables can be used for storing temporary result of Function.
=>The Values of Local Variables can be used inside of same Function Definition but not
possible to access in other part of the program and in other Function Definition.
---------------------------------------------------------------------------------------------------------------------------------
------
=>Global variables are those which are used for Representing Common values for Multiple Different
Function calls and Saves the Memory Space.
=>Global variables must be defined before all function calls. So that we can access the global variable
values in all the function definitions. Otherwise we can't access.

=>Syntax:
Var1=Val1
Var2=Val2
-------------
Var-n=Val-n

def functionname1(.....):
var22=val22
var23=val23
------------------
def functionname2(.....):
var32=val32
var33=val33

=>here Var1,Var2...Var-n are called Global variables for functiondefinition1() and functiondefinition2()
=>here Var22,Var23... are called Local Varbales variables functiondefinition1()
=>here Var32,Var33... are called Local Varbales variables in functiondefinition2()

=====================================================================
Examples:
-------------------------------
#globallocalvarex3.py
def learnML():
sub1="Machine Learning" # here sub1 is called Local Variable
print("\nTo Learn and Code in '{}' , we use '{}' Programming ".format(sub1,lang))
#print(sub2,sub3)---Error bcoz sub2 and subj3 are local variables in other Functions

def learnDL():
sub2="Deep Learning" # here sub2 is called Local Variable
print("\nTo Learn and Code in '{}' , we use '{}' Programming ".format(sub2,lang))
#print(sub1,sub3)---Error bcoz sub1 and subj3 are local variables in other Functions
def learnIOT():
sub3="IOT" # here sub3 is called Local Variable
print("\nTo Learn and Code in '{}' , we use '{}' Programming ".format(sub3,lang))
#print(sub1,sub2)---Error bcoz sub1 and subj1 are local variables in other Functions
#main program
lang="PYTHON" # Global Variable
learnML()
learnDL()
learnIOT()
=================================X====================================

Examples:
----------------------
#globallocalvarex4.py
def learnML():
sub1="Machine Learning" # here sub1 is called Local Variable
print("\nTo Learn and Code in '{}' , we use '{}' Programming ".format(sub1,lang))

def learnDL():
sub2="Deep Learning" # here sub2 is called Local Variable
print("\nTo Learn and Code in '{}' , we use '{}' Programming ".format(sub2,lang))

def learnIOT():
sub3="IOT" # here sub3 is called Local Variable
print("\nTo Learn and Code in '{}' , we use '{}' Programming ".format(sub3,lang))

#main program
learnML()
learnDL()
learnIOT()
lang="PYTHON" # Global Variable --here we can' t access Variable lang in learnML(), learnDL() and
LearnIOT() bcoz It is defined after Function Call.
=======================================================================
------------------------------------
Examples:
------------------------------------
#GlobalLocalVarEx1.py
lang="PYTHON Prog" # Global Variable
def learnML():
crs1="ML" # Here crs1 is called Local Variable
#print(crs2,crs3)---NameError, bcoz crs2 and crs3 are locaal Variables in learnDL() and
learnAI()
print("\nTo Learn '{}' , we need to learn '{}'".format(crs1,lang))

def learnDL():
crs2="DL" # Here crs2 is called Local Variable
#print(crs1,crs3)--NameError, bcoz crs1 and crs3 are local Variables in learnML() and learnAI()
print("\nTo Learn '{}' , we need to learn '{}'".format(crs2,lang))

def learnAI():
crs3="AI" # Here crs3 is called Local Variable
#print(crs1,crs2)--NameError, bcoz crs1 and crs1 are locaal Variables in learnML() and
learnDL()
print("\nTo Learn '{}' , we need to learn '{}'".format(crs3,lang))

#main program
learnML()
learnDL()
learnAI()

#GlobalLocalVarEx2.py
def learnML():
crs1="ML" # Here crs1 is called Local Variable
#print(crs2,crs3)---NameError, bcoz crs2 and crs3 are locaal Variables in learnDL() and
learnAI()
print("\nTo Learn '{}' , we need to learn '{}'".format(crs1,lang))

lang="PYTHON Prog" # Global Variable

def learnDL():
crs2="DL" # Here crs2 is called Local Variable
#print(crs1,crs3)--NameError, bcoz crs1 and crs3 are local Variables in learnML() and learnAI()
print("\nTo Learn '{}' , we need to learn '{}'".format(crs2,lang))

def learnAI():
crs3="AI" # Here crs3 is called Local Variable
#print(crs1,crs2)--NameError, bcoz crs1 and crs1 are locaal Variables in learnML() and
learnDL()
print("\nTo Learn '{}' , we need to learn '{}'".format(crs3,lang))

#main program
learnML()
learnDL()
learnAI()
------------------------------------
Examples:
------------------------------------
#GlobalLocalVarEx3.py
def learnML():
crs1="ML" # Here crs1 is called Local Variable
#print(crs2,crs3)---NameError, bcoz crs2 and crs3 are locaal Variables in learnDL() and
learnAI()
print("\nTo Learn '{}' , we need to learn '{}'".format(crs1,lang))

def learnDL():
crs2="DL" # Here crs2 is called Local Variable
#print(crs1,crs3)--NameError, bcoz crs1 and crs3 are local Variables in learnML() and learnAI()
print("\nTo Learn '{}' , we need to learn '{}'".format(crs2,lang))

def learnAI():
crs3="AI" # Here crs3 is called Local Variable
#print(crs1,crs2)--NameError, bcoz crs1 and crs1 are locaal Variables in learnML() and
learnDL()
print("\nTo Learn '{}' , we need to learn '{}'".format(crs3,lang))

#main program
lang="PYTHON Prog" # Global Variable
learnML()
learnDL()
learnAI()

------------------------------------
Examples:
------------------------------------
#GlobalLocalVarEx4.py
def learnML():
crs1="ML" # Here crs1 is called Local Variable
#print(crs2,crs3)---NameError, bcoz crs2 and crs3 are locaal Variables in learnDL() and
learnAI()
print("\nTo Learn '{}' , we need to learn '{}'".format(crs1,lang))

def learnDL():
crs2="DL" # Here crs2 is called Local Variable
#print(crs1,crs3)--NameError, bcoz crs1 and crs3 are local Variables in learnML() and learnAI()
print("\nTo Learn '{}' , we need to learn '{}'".format(crs2,lang))

def learnAI():
crs3="AI" # Here crs3 is called Local Variable
#print(crs1,crs2)--NameError, bcoz crs1 and crs1 are locaal Variables in learnML() and
learnDL()
print("\nTo Learn '{}' , we need to learn '{}'".format(crs3,lang))

#main program
#learnML()---> lang can't access in learnML() bcoz it is used after this call
lang="PYTHON Prog" # Global Variable
learnDL() # lang can be accessed on learnDL() and learnAI()
learnAI()
global key word concept programs:

======================================
global key word
======================================
=>When we want MODIFY the GLOBAL VARIABLE values in side of function defintion then global variable
names must be preceded with 'global' keyword otherwise we get "UnboundLocalError: local variable names
referenced before assignment"

Syntax:
-----------
var1=val1
var2=val2
var-n=val-n # var1,var2...var-n are called global variable names.
------------------
def fun1():
------------------------
global var1,var2...var-n
# Modify var1,var2....var-n
--------------------------
def fun2():
------------------------
global var1,var2...var-n
# Modify var1,var2....var-n
--------------------------

Examples:
-----------------------
#globalvarex1.py
a=10
def access1():
print("Val of a=",a) # Here we are accessing the global variable 'a' and No Need to use global kwd.

#main program
access1()
---------------------------------------
#globalvarex2.py
a=10
def access1():
global a # refering global Varaible before its updation / Modification
a=a+1 # Here we are modifying the global variable value then we need to use global keyword.
print("Val of a inside of access1()=",a) # 11
#main program
print("Val of a in main before access1():",a) # 10
access1()
print("Val of a in main after access1():",a) # 11
---------------------------------------------------------------------------------
Examples:
------------------
#globalvarex3.py
def update1():
global a,b # refering global Variables.
a=a+1 #updating global Variable a
b=b+1 #updating global Variable b
def update2():
global a,b # refering global Variables.
a=a*10 #updating global Variable a
b=b*10 #updating global Variable b
#main program
a,b=1,2 # here a and b are called Global Variables
print("Val of a={} and Value of b={} in main program before update functions :".format(a,b))
# Val of a=1 and Value of b=2 in main program before update functions :
update1()
print("Val of a={} and Value of b={} in main program after update1():".format(a,b))
#Val of a=2 and Value of b=3 in main program after update1():
update2()
print("Val of a={} and Value of b={} in main program after update2():".format(a,b))
#Val of a=20 and Value of b=30 in main program after update1():
================================X=====================================
------------------------------------
Examples:
------------------------------------
#GlobalVarModificationEx1.py
a=10 # Global variable
def accessgv():
print("val of a in accessgv()--GV=",a) # Here are acessing Global Variable

#main progran
print("val of a in main program=",a)
accessgv()

------------------------------------
Examples:
------------------------------------
#GlobalVarModificationEx2.py
a=10 # Global Variable
def modify1():
global a
a=a+1

def modify2():
global a
a=a*2

#main program
print("val of a in main program before modify1()=",a)
modify1()
print("val of a in main program after modify1()=",a)
modify2()
print("val of a in main program after modify2()=",a)

------------------------------------
Examples:
------------------------------------
#GlobalVarModificationEx3.py
a,b=0,0 # global Variables
def update1():
global a,b
a=a+1
b=b+1

def update2():
global a,b
a=a*2
b=b*10

#main program
print("Val of a in main program before update1()=",a)#0
print("Val of a in main program before update1=",b)#0
update1()
print("Val of a in main program after update1()=",a)#1
print("Val of a in main program after update1()=",b)#1
update2()
print("Val of a in main program after update2()=",a) # 2
print("Val of a in main program after update2()=",b) # 10

global and local variables and globals() concept programs:

============================================
global and local variables and globals()
============================================
=>When we come acrosss same global Variable names and Local Vraiable Names in same function
definition then PVM gives preference for local variables but not for global variables.
=>In this context, to extract / retrieve the values of global variables names along with local variables, we
must use globals() and it returns an object of <class,'dict'> and this dict object stores all global variable
Names as Keys and global variable values as values of value.

=>Syntax:-
var1=val1
var2=val2
--------------
var-n=val-n # var1, var2...var-n are called global Variables
def functionname():
------------------------
var1=val11
var2=val22
-----------------
var-n=val-nn # var1, var2...var-n are called local Variables
# Extarct the global variables values
dictobj=globals()
------------------------
globalval1=dictobj['var1'] # or dictobj.get("var1") or globals()['var1']
globalval2=dictobj['var2'] # or dictobj.get("var2") or globals()['var2']
-----------------------------------------------------
-----------------------------------------------------
==================================================================
Examples:
============
#globalsfunex3.py
a=10
b=20
c=30
d=40
def operations():
obj=globals()
for gvn,gvv in obj.items():
print("\t{}---->{}".format(gvn,gvv))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", obj['a'])
print("Val of b=", obj['b'])
print("Val of c=", obj['c'])
print("Val of d=", obj['d'])
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", obj.get('a'))
print("Val of b=", obj.get('b'))
print("Val of c=", obj.get('c'))
print("Val of d=", obj.get('d'))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", globals().get('a'))
print("Val of b=", globals().get('b'))
print("Val of c=", globals().get('c'))
print("Val of d=", globals().get('d'))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", globals()['a'])
print("Val of b=", globals()['b'])
print("Val of c=", globals()['c'])
print("Val of d=", globals()['d'])
print("="*50)
=================================================
#main program
operations()
==================================================
Examples:
-----------------------
#Program for demonstrating globals()
#globalsfunex2.py
a=10
b=20
c=30
d=40 # Here a,b,c,d are called Global Variables
def operation():
a=100
b=200
c=300
d=400 # Here a,b,c,d are called Local Variables
res=a+b+c+d+globals()['a']+globals().get('b')+globals()['c']+globals()['d']
print(res)

#main program
operation()

====================================X=================================

------------------------------------
Examples:
------------------------------------
#globalsfunex1.py
a=10
b=20
c=30
d=40 # Here a,b,c,d are called global Variables
def operations():
x=1
y=2
z=3
k=4 # Here x,y,z,k are called local Variables
res=a+b+c+d+x+y+z+k
print("Val of res=",res)

#main program
operations()

------------------------------------
Examples:
------------------------------------
#globalsfunex2.py
a=10
b=20
c=30
d=40 # Here a,b,c,d are called global Variables
def operations():
a=1
b=2
c=3
d=4 # Here a,b,c,d are called local Variables
print("Val of a--Local=",a)
print("Val of b--Local=",b)
print("Val of c--Local=",c)
print("Val of d--Local=",d)
print("Val of a--global=",globals()['a'])
print("Val of b--global=",globals()['b'])
print("Val of c--global=",globals()['c'])
print("Val of d--global=",globals()['d'])
res=a+b+c+d+globals().get('a')+globals().get('b')+globals()['c']+globals().get('d')
print("sum of local and global variable values=",res)

#main program
operations()

------------------------------------
Examples:
------------------------------------
#globalsfunex2.py
a=10
b=20 # here a and b are called global variables
def operation():
d=globals() # here d is an object <class,dict>---
print("-"*50)
print("Programmer-defined Global Variables")
print("-"*50)
print("Val of a-GV=",d['a'])
print("Val of a-GV=",d['b'])
print("-"*50)
print("Programmer-defined Global Variables")
print("-"*50)
print("Val of a-GV=",d.get('a'))
print("Val of a-GV=",d.get('b'))
print("-"*50)
print("Programmer-defined Global Variables")
print("-"*50)
print("Val of a-GV=",globals().get('a'))
print("Val of a-GV=",globals().get('b'))
print("-"*50)
print("Programmer-defined Global Variables")
print("-"*50)
print("Val of a-GV=",globals()['a'])
print("Val of a-GV=",globals()['b'])
print("-"*50)

#main program
operation()
------------------------------------
Examples:
------------------------------------
#globalsfunex4.py
a=10
b=20
c=30
d=40 # Here a,b,c,d are called global Variables
def operations():
global c,d
c=c+1 # c=31
d=d+1 # d=41
e1=globals()['c']
e2=globals()['d']
a=1
b=2
c=3
d=4 # Here a,b,c,d are called local Variables
d1=globals()
print("Val of a--Local=",a)
print("Val of b--Local=",b)
print("Val of c--Local=",c)
print("Val of d--Local=",d)
print("Val of a--global=",d1.get('a'))
print("Val of b--global=",d1.get('b'))
print("Val of c--global=",e1)
print("Val of d--global=",e2)
res=a+b+c+d+d1.get('a')+d1.get('b')+e1+e2
print("sum of local and global variable values=",res)

#main program
operations()

Anonymous Functions OR Lambda Functions Programs:

==========================================================
Anonymous Functions OR Lambda Functions
==========================================================
=>Anonymous Functions are those which does not contain any name.
=>The purpose of Anonymous Functions is that " To Perform Instant Operations".
=>Instant Operations are those which are used at that point of time only and not longer
interested to re-use in other part of program.
=>Anonymous Functions contains single executable statement only.
=>To define Anonymous Functions, we use a keyword "lambda". Hence Anonymous
Functions are called Lambda Functions
=>Anonymous Functions returns its result automatically (No need to use return statement).
-------------------
=>Syntax:
-------------------
varname=lambda params-list : expression
---------------------------------
Explanation:
---------------------------------
=>Here varname is an object of <class,'function'> and it itself can be for calling Anonymous
Functions.
=>lambda is a keword used for defining Anonymous Functions.
=>params-list represents list of variable names used for holding input values coming from
function calls.
=>expression represents single executable statement.
-------------------------------------------------
By Using Normal Function Def Normal Function Call
-------------------------------------------- -------------------------------------
-------
def addop(a,b):
res=addop(10,20)
c=a+b
print(res)------30
return c
-------------------------------------------------------------------------------------------------------------------
By Using Anonymous Function Def Anonymous Function Call
--------------------------------------------------- ------------------------------------------------
sumop=lambda a,b : a+b res=sumop(10,20)

print(res) # 30
------------------------------------
Examples:
------------------------------------
#Program for all aops with Anoinymous Functions with Menu driven
#anonymousaop.py
import sys
def menu():
print("-"*50)
print("\tArithmetic Operation:")
print("-"*50)
print("\t1.Addition:")
print("\t2.Substraction:")
print("\t3.Multiplication:")
print("\t4.Division:")
print("\t5.Modulo Div:")
print("\t6.Exponentiation:")
print("\t7.Exit:")
print("-"*50)

#Anonymous Functions
addop=lambda a,b:a+b
subop=lambda a,b:a-b
mulop=lambda k,v:k*v
divop=lambda k,v:k/v
floordiv=lambda a,b:a//b
modop=lambda a,b:a%b
expoop=lambda x,y:x**y

#main program
while(True):
menu()
ch=int(input("Enter ur Choice:"))
match (ch):
case 1:
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
res=addop(a,b)
print("sum({},{})={}".format(a,b,res))
case 2:
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
res=subop(a,b)
print("sub({},{})={}".format(a,b,res))
case 3:
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
res=mulop(a,b)
print("mul({},{})={}".format(a,b,res))
case 4:
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
res1=divop(a,b)
res2=floordiv(a,b)
print("Div({},{})={}".format(a,b,res1))
print("Floor Div({},{})={}".format(a,b,res2))
case 5:
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
res=modop(a,b)
print("mod({},{})={}".format(a,b,res))
case 6:
a=float(input("Enter Base:"))
b=float(input("Enter Power:"))
res=expoop(a,b)
print("exp({},{})={}".format(a,b,res))
case 7:
print("\nThx for this Program!")
sys.exit()
case _:
print("\nUr Choice of Operation is Wrong--try again")

------------------------------------
Examples:
------------------------------------
#Program for all aops with Anoinymous Functions with Menu driven
#anonymousaop1.py
import sys
def menu():
print("-"*50)
print("\tArithmetic Operation:")
print("-"*50)
print("\t1.Addition:")
print("\t2.Substraction:")
print("\t3.Multiplication:")
print("\t4.Division:")
print("\t5.Modulo Div:")
print("\t6.Exponentiation:")
print("\t7.Exit:")
print("-"*50)
def readvalues(op):
a=float(input("Enter First Value {}".format(op)))
b=float(input("Enter Second Value {}".format(op)))
return a,b

#Anonymous Functions
addop=lambda a,b:a+b
subop=lambda a,b:a-b
mulop=lambda k,v:k*v
divop=lambda k,v:k/v
floordiv=lambda a,b:a//b
modop=lambda a,b:a%b
expoop=lambda x,y:x**y

#main program
while(True):
menu()
ch=int(input("Enter ur Choice:"))
match (ch):
case 1:
a,b=readvalues("Addition:")
print("sum({},{})={}".format(a,b,addop(a,b)))
case 2:
k,v=readvalues("Substraction:")
print("sub({},{})={}".format(k,v,subop(k,v)))
case 3:
a,b=readvalues("Multiplication:")
print("mul({},{})={}".format(a,b,mulop(a,b)))
case 4:
a,b=readvalues("Div / Floor Div:")
print("Div({},{})={}".format(a,b,divop(a,b)))
print("Floor Div({},{})={}".format(a,b,floordiv(a,b)))
case 5:
a,b=readvalues("Modulo Div:")
print("mod({},{})={}".format(a,b,modop(a,b)))
case 6:
a=float(input("Enter Base:"))
b=float(input("Enter Power:"))
print("exp({},{})={}".format(a,b,expoop(a,b)))
case 7:
print("\nThx for this Program!")
sys.exit()
case _:
print("\nUr Choice of Operation is Wrong--try again")

------------------------------------
Examples:
------------------------------------
#Proghram for adding two values by using Anonymous Functions.
#AnonymousEx1.py
def sumop(a,b):
c=a+b
return c

#Anonymous Functions
addop=lambda a,b:a+b

#main program
print("type of sumop=",type(sumop))
res=sumop(10,20)
print("sum by using Normal Function=",res)
print("================OR===================")
print("type of addop=",type(addop))
res=addop(25,35)
print("Sum by using Anonymous Functions=",res)

------------------------------------
Examples:
------------------------------------
#bigsmall.py
big=lambda a,b,c:"All Values are Equal" if(a==b==c) else a if (b<a>c) else b if(a<b>c) else c

small=lambda a,b,c:"All Values are Equal" if(a==b) and(b==c) else a if(a<b) and (a<c) else b if (b<a) and
(b<c) else c

#main program
a,b,c=float(input("Val of a:")),float(input("Val of b:")),float(input("Val of c:"))
print("big({},{},{})={}".format(a,b,c,big(a,b,c)))
print("small({},{},{})={}".format(a,b,c,small(a,b,c)))

===================================================
Special Functions in Python
===================================================
=>In Python Programming, we have 3 types of special Functions. They are
1) filter()
2) map()
3) reduce()

filter() concept programs:

--------------------------------------------
1) filter():
--------------------------------------------
=>filter() is used for "Filtering out some elements from list of elements by applying to function".
=>Syntax:- varname=filter(FunctionName, Iterable_object)

---------------------
Explanation:
---------------------
=>here 'varname' is an object of type <class,'filter'> and we can convert into any iteratable object by using
type casting functions.
=>"FunctionName" represents either Normal function or anonymous functions.
=>"Iterable_object" represents Sequence, List, set and dict types.
=>The execution process of filter() is that " Each Value of Iterable object sends to Function Name. If the
function return True then the element will be filtered. if the Function returns False then that element will
be neglected/not filtered ". This process will be continued until all elements of Iterable object completed.
------------------------------------
Examples:
------------------------------------
#FilterEx1.py

def even(n):
if n%2==0:
return True
else:
return False

def odd(n):
if(n%2!=0):
return True
else:
return False

#main program
lst=[12, 45, 67, 23, 24, 56,17,28]
fobj=filter(even,lst)
print("type of fobj=",type(fobj)) # type of fobj= <class 'filter'>
print("content of fobj=",fobj) # content of fobj= <filter object at 0x000001565B299DB0>
print("-------------------------------------")
evenlist=list(fobj)
print("Given List=",lst)
print("List of even Numbers=",evenlist)
fobj1=filter(odd,lst)
oddlist=tuple(fobj1)
print("List of Odd Numbers=",oddlist)

------------------------------------
Examples:
------------------------------------
#FilterEx2.py

even=lambda n:n%2==0 # Anonymous Function


odd=lambda k:k%2!=0 # Anonymous Function
#main program
lst=[12, 45, 67, 23, 24, 56,17,28,16,122,121]
evenlist=list(filter(even,lst))
oddlist=tuple(filter(odd,lst))
print("Given List=",lst)
print("List of even Numbers=",evenlist)
print("List of Odd Numbers=",oddlist)

#Program for filtering +Ve and -Ve Numbers from list of numbers.
#FilterEx3.py
positive=lambda n: n>0
negative=lambda n:n<0

#main program
lst=[10,-23,34,56,-67,-12,-34,0,45,-38]
pslist=list(filter(positive,lst))
nglist=list(filter(negative,lst))
print("Given List=",lst)
print("Possitive Elements List=",pslist)
print("Negative Elements List=",nglist)

------------------------------------
Examples:
------------------------------------
#Program for filtering +Ve and -Ve Numbers from list of numbers.
#FilterEx3.py

lst=[12,45,-56,-78,0,0,12,-45]

pslist=list(filter(lambda n: n>0 , lst))


nglist=list(filter(lambda n:n<0, lst))
print("Given List=",lst)
print("Possitive Elements List=",pslist)
print("Negative Elements List=",nglist)

------------------------------------
Examples:
------------------------------------
#Program for filtering +Ve and -Ve Numbers from list of numbers.
#FilterEx5.py
def readvalues():
lst=[]
n=int(input("Enter How Many Values u Have:"))
if(n<=0):
return lst
else:
print("Enter {} Values:".format(n))
for i in range(1,n+1):
lst.append(int(input()))
return lst

#main program
lst=readvalues()
print("Given List=",lst)
if(len(lst)>0):
pslist=list(filter(lambda n: n>0 , lst))
nglist=list(filter(lambda n:n<0, lst))
print("Possitive Elements List=",pslist)
print("Negative Elements List=",nglist)
else:
print("List is empty--No More Filtering")

------------------------------------
Examples:
------------------------------------
#Program for filtering +Ve and -Ve Numbers from list of numbers.
#FilterEx6.py
print("Enter List of values separated by space:")
lst=[int(val) for val in input().split() ]
print("Given List=",lst)
if(len(lst)>0):
pslist=list(filter(lambda n: n>0 , lst))
nglist=list(filter(lambda n:n<0, lst))
print("Possitive Elements List=",pslist)
print("Negative Elements List=",nglist)
else:
print("List is empty--No More Filtering")

------------------------------------
Examples:
------------------------------------
#Program for filtering vowels from given sentence
#FilterEx7.py
line=input("\nEnter a Line of Text:")
print("\nGiven Line={}".format(line))
#Filtering for Vowels
vlist=list(filter(lambda ch: ch.lower() in ['a','e','i','o','u'], line))
print("Vowels List={} and Number of Vowels={}".format(vlist,len(vlist)))
clist=list(filter(lambda ch: ch.lower() not in ['a','e','i','o','u'] and not(ch.isspace()) and not(ch.isdigit()) ,
line))
print("Consonant List={} and Number of Cons={}".format(clist,len(clist)))

------------------------------------
Examples:
------------------------------------
#Program for filtering special symbols
#FilterEx8.py
line=input("\nEnter a Line of Text:") # "$Py8 # hon"
print("\nGiven Line={}".format(line))
spslist=list(filter(lambda ch:not (ch.isalpha() or ch.isdigit() or ch.isalnum() ),line) )
print("Special Symbols lis=",spslist)

map() concept programs:

======================
2) map()
=======================
=>map() is used for obtaining new Iterable object from existing iterable object by applying old iterable
element to the function.
=>In otherwords, map() is used for obtaining new list of elements from existing existing list of elements
by applying old list elements to the function.

=>Syntax:- varname=map(FunctionName,Iterable_object)

=>here 'varname' is an object of type <class,map'> and we can convert into any iteratable object by using
type casting functions.
=>"FunctionName" represents either Normal function or anonymous functions.
=>"Iterable_object" represents Sequence, List, set and dict types.
=>The execution process of map() is that " map() sends every element of iterable object to the specified
function, process it and returns the modified value (result) and new list of elements will be obtained". This
process will be continued until all elements of Iterable_object completed.
----------------------------------------------------------------------

Examples:
------------------------------------

#Program for obtaining Square for every list of list object


#mapex1.py
def square(n):
return n**2

#main program
lst=[2,5,9,3,6,12,14]
mapobj=map(square,lst)
print("type of mapobj=",type(mapobj)) # <class 'map'>
sqlist=list(mapobj)
print("\nOriginal List=",lst)
print("Square list=",sqlist)

Examples:
------------------------------------
#Program for obtaining Square for every list of list object
#mapex2.py

square=lambda n:n**2 # Anonymous Function

#main program
lst=[2,5,9,3,6,12,14,-19]
mapobj=map(square,lst)
print("type of mapobj=",type(mapobj)) # <class 'map'>
sqlist=list(mapobj)
print("\nOriginal List=",lst)
print("Square list=",sqlist)

Examples:
------------------------------------
#Program for obtaining Square for every list of list object
#mapex3.py
lst=[2,5,9,3,6,12,14,-19]
sqlist=tuple(map(lambda n:n**2,lst))
print("\nOriginal List=",lst)
print("Square list=",sqlist)

Examples:
------------------------------------
# Program for obtaining Square for every list of list object
#MapEx4.py
def readvalues():
lst=[]
n=int(input("Enter How Many Values u Have:"))
if(n<=0):
return lst
else:
print("Enter {} Values:".format(n))
for i in range(1,n+1):
lst.append(int(input()))
return lst

#main program
lst=readvalues()
print("Given List=",lst)
if(len(lst)>0):
sqlist=list(map(lambda n:n**2,lst))
print("Square List=",sqlist)
else:
print("List is Empty--Nothing is there to map:")
# Program for obtaining New Sal list from old sal list
#MapEx5.py
def readsal():
lst=[]
n=int(input("Enter How Many Sals u Have:"))
if(n<=0):
return lst
else:
print("Enter {} Salary:".format(n))
for i in range(1,n+1):
lst.append(float(input()))
return lst
#main program
sallist=readsal()
print("Original Sal List=",sallist)
if(len(sallist)>0):
newsallist=list(map(lambda sal:sal*1.15, sallist))
print("Hiked Sal List=",newsallist)
else:
print("List is Empty--Nothing is there to map:")

Examples:
------------------------------------
#MapEx6.py
def readvalues():
lst=[]
n=int(input("Enter How Many Values u Have:"))
if(n<=0):
return lst
else:
print("Enter {} Value:".format(n))
for i in range(1,n+1):
lst.append(float(input()))
return lst
#main program
lst=readvalues()
print("Original List=",lst)
if(len(lst)>0):
pslist=list(filter(lambda n:n>0,lst))
pslistsqrt=list(map(lambda val:val**0.5,pslist))

nglist=list(filter(lambda n:n<0,lst))
ngsqlist=list(map(lambda n:n**2,nglist))
print("\nPossitive Elements by Filtering=",pslist)
print("Possitive Elements Square Roots=",pslistsqrt)
print("Sum of pssqlist=",sum(pslistsqrt))
print("\nNegative Elements by Filtering=",nglist)
print("Negative Elements Squars=",ngsqlist)
print("Sum of nglist=",sum(ngsqlist))
else:
print("List is Empty--Nothing is there to map:")
==========================================
List comprehension
==========================================
=>The purpose of List comprehension is that to read the values dynamically from key board separated by a
delimeter ( space, comma, colon..etc) .
=>List comprehension is the most effective way for reading the data for list instead tradtional reading the
data.
=>Syntax:- listobj=[ expression for varname in Iterable_object ]
=>here expression represents either type casting or mathematical expression

Examples:
----------------------
print("Enter List of values separated by space:") # [10,2,222,50,10,4,55,-3,0,22]
lst= [float(val) for val in input().split() ]
print("content of lst",lst)

Examples:
------------------
lst=[4,3,7,-2,6,3]
newlst=[ val*2 for val in lst ]
print("new list=",newlst) # [ 8, 6, 14,-4,12,6 ]

Examples:
------------------------------------
#ListCompreEx1.py
print("Enter List of Values separated by Space:")
lst=[int (val) for val in input().split() ]
print(lst)
Examples:
------------------------------------
#ListCompreEx2.py
print("Enter list of values separated by comma:")
explst=[ int(val)**int(val) for val in input().split(",") ]
print("Exp List=",explst)
print("===============OR==================")
print("Enter list of values separated by comma:")
lst=[ int(val) for val in input().split(",") ] # lst = 2,3,4,5,6
explist=[val**val for val in lst]
print("Oginal List=",lst)
print("Exp List=",explist)

Examples:
------------------------------------
#ListCompreEx3.py
print("Enter List of Values separated by Space:")
lst=[int (val) for val in input().split() ]
print("Given List=",lst)
lst.sort()
print("Elements in Ascending Order:{}".format(lst))
lst.sort(reverse=True)
print("Elements in Descending Order:{}".format(lst))

Examples:
------------------------------------
#ListCompreEx4.py
print("Enter List of Names separated by Space:")
lst=[ str(val) for val in input().split() ]
print("Given List=",lst)
lst.sort()
print("Elements in Ascending Order:{}".format(lst))
lst.sort(reverse=True)
print("Elements in Descending Order:{}".format(lst))

Examples:
------------------------------------
#ListCompreEx5.py
print("Enter List of Names separated by Space:")
lst={ str(val) for val in input().split() }
print("Type=",type(lst))
print("Given List=",lst)
"""lst.sort()
print("Elements in Ascending Order:{}".format(lst))
lst.sort(reverse=True)
print("Elements in Descending Order:{}".format(lst))"""

================================
reduce()
================================
=>reduce() is used for obtaining a single element / result from given iterable object by applying to a
function.
=>Syntax:-
varname=reduce(function-name,iterable-object)

=>here varname is an object of int, float,bool,complex,str only


=>The reduce() belongs to a pre-defined module called" functools".
---------------------------------------
Internal Flow of reduce()
---------------------------------------
step-1:- Initially,reduce() selects two First values of Iterable object and place them in First var
and Second var .
step-2:- The function-name(lambda or normal function) utilizes the values of First var and
Second var applied to the specified logic and obtains the result.
Step-3:- reduce () places the result of function-name in First variable and reduce()
selects the succeeding element of Iterable object and places in second variable.
Step-4: repeat Step-2 and Step-3 until all elements completed in
Iterable object and returns the result of First Variable

reduce() concept programs:


-----------------------------------
Examples:
------------------------------------
#program for finding sum of list of values
#reduceex1.py
import functools
lst=[10,20,30,40,50,60,-10]
res=functools.reduce(lambda x,y:x+y,lst)
print("sum=",res)
Examples:
------------------------------------
#program for finding sum of list of values
#reduceex2.py
import functools

def sumop(a,b):
return (a+b)

#main program
print("Enter List of values separated space:")
lst=[float(val) for val in input().split()]
res=functools.reduce(sumop,lst) # here sumop is the name of normal function
print("sum=",res)
------------------------------------------------------------------------------------------------------------
Examples:
------------------------------------
#Program obtaining max value from list of values
#reduceex3.py
import functools
print("Enter List of values separated space:")
lst=[float(val) for val in input().split()]
big=functools.reduce(lambda x,y: x if x>y else y, lst)
print("big({})={}".format(lst,big))
------------------------------------------------------------------------------------------------------------
Examples:
------------------------------------
#Program for accepting list of values and find sum of +ve and -ve by using reduce() and filter
#ReduceFilterEx1.py
import functools
print("Enter List of values separated space:")
lst=[float(val) for val in input().split()] # [10,-20,30,40,-50]
print("\nGiven List={}".format(lst))
psnumssum=functools.reduce(lambda x,y:x+y,list(filter(lambda x: x>0,lst)))
nsnumssum=functools.reduce(lambda x,y:x+y,list(filter(lambda x: x<0,lst)))
print("Possive Numbers Sum=",psnumssum)
print("Negative Numbers Sum=",nsnumssum)
Examples:
-----------------------------
#FilterMapReduceEx.py
import functools
print("Enter List of Salaries separated space(0-1000):")
sallst=[float(sal) for sal in input().split() if float(sal)>=0 and float(sal)<=1000]
print("Salary List=",sallst)
# Logic
salsum_0_500_15per=functools.reduce(lambda sal1,sal2 : sal1+sal2,list(map(lambda
sal:sal*1.15,tuple(filter (lambda sal:sal>=0 and sal<=500,sallst)))))
print("Total Salary(0--500--15%)=",salsum_0_500_15per)

salsum_501_1000_30per=functools.reduce(lambda sal1,sal2 : sal1+sal2,list(map(lambda


sal:sal*1.30,tuple(filter (lambda sal:501<=sal<=1000,sallst)))))
print("Total Salary(501--1000-30%)=",salsum_501_1000_30per)
----------------------------------------------------------------------------------------------------------------
Examples:
-----------------------------
#FilterReduceEx.py
import functools
print("Enter List of Names separated space:")
lst=[val for val in input().split()]
length5more=list(filter(lambda name: len(name)>=5, lst))
print("Words=",length5more)
wordconcat=functools.reduce(lambda w1,w2:w1+"-->"+w2,length5more)
print("Concat Words=",wordconcat)
-----------------------------------------------------------------------------------------------------------
Examples:
----------------------------
#FilterReduceEx1.py
import functools
print("Enter List of Names separated space:")
lst=[val for val in input().split()]
wordconcat=functools.reduce(lambda w1,w2:w1+"-->"+w2, list(filter(lambda word:len(word)==3,lst)))
print("Concat Words=",wordconcat)
------------------------------------------------------------------------------------------------------------
Modules in Python Development of Programmer-Defined Module
Number of approaches to re-use Modules Programs.
-----------------------------------------------------------------------------------------------------------

=============================================
Modules
=============================================
Index
------------
=>Purpose of Modules
=>Definition of Module
=>Types of Modules
a) Pre-defined Modules
b) Programmer-defined modules
=>Development Programmer-Defined Modules
=>Techniques for Re-Using the Modules
1) by using import statement (4 syntaxes
2) By using from ... import statement (3 syntaxes )
=>Programming Examples
=>Re-loding the Modules
=>Programming Examples
=============================================
Modules in Python
=============================================
=>We know that Functions concept makes us understand How to perform operations and we can re-use within
the same program but not able to re-use the functions across the programs.
=>To reuse the functions and global variables across the programs, we must use the concept of MODULES.
---------------------------------------
=>Definition of Modules:
---------------------------------------
=>A Module is a collection of variables (global variables) , Functions and Classes.
-----------------------------------
=>Types of Modules:
-----------------------------------
=>In Python Programming, we have two types of Modules. They are
1) Pre-defined (or) Built-in Modules
2) Programmer or user or custom-defined modules.
-----------------------------------------------------
1) Pre-defined (or) Built-in Modules:
----------------------------------------------------
=>These modules are developed by Python Language Developers and they are avialable in Python Software
(APIs) and they are used python programmers for dealing with Universal Requirements.

Examples: math cmath functools sys calendar os


re threading pickle random.......etc

=>Out of many pre-defined modules, in python programming one implicit pre-defined module imported to
every python program called "builtins" .
---------------------------------------------------------------------------
2) Programmer or user or custom-defined modules:
---------------------------------------------------------------------------------------
=>These modules are developed by Python Programmers and they are avialable in Python Project and they are
used by other python programmers who are in project development to deal with common requirements.
=>Examples:- aop mathsinfo icici ......etc
---------------------------------------------------------------------------

=================================================
Development of Programmer-Defined Module
=================================================
=>To develop Programmer-Defined Modules, we must use the following steps

Step-1 : Define Variables (Global variables)


Step-2: Define Functions
Step-3: Define Classes

=>After developing step-1, step-2 and step-3 , we must save on some file name with an extension .py
(FileName.py) and it is treated as module name.
=>When a file name treated as a module name , internally Python execution environment creates a folder
automatically on the name of __pycache__ and it contains module name on the name "filename.cpython-
310.pyc ".
-------------------
Examples:
------------------
__pycache__ <-----Folder Name
-------------------------------------------
aop.cpathon-310.pyc <-------------------Module Name
mathsinfo.cpython-310.pyc<--------------Module Name
icici.cpython-310.pyc<----------------------Module Name
----------------------------------------------
===============================================
Number of approaches to re-use Modules
===============================================
=>We know that A Module is a collection of variables, Functions and Classes.
=>To re-use the features(Variable Names, Function Names and Class Names ) of module, we have 2
approaches.They are
1) By using import statement
2) By using from.... import statement.
---------------------------------------------------------------------------------------
1) By using import statement:
---------------------------------------------------------------------------------------
=>'import' is a keyword
=>The purpose of import statement is that "To refer or access the variable names, function names and class
names in current program"
=>we can use import statement in 4 ways.
-------------------
=>Syntax-1: import module name
-------------------
=>This syntax imports single module
----------------
Example: import icici
import aop
import mathsinfo
--------------------------------------------------------------------
=>Syntax-2: import module name1, module name2....Module name-n
-------------------
=>This syntax imports multiple modules
----------------
Example: import icici,aop,mathsinfo
----------------------------------------------------------------------------------------------------------------------------
=>Syntax-3: import module name as alias name
-------------------
=>This syntax imports single module and aliased with another name
----------------
Example: import icici as i
import aop as a
import mathsinfo as m
----------------------------------------------------------------------------------------------------------------------------
=>Syntax-4: import module name1 as alias name, module name2 as alias
name......module name-n as alias name
-------------------
=>This syntax imports multiple modules and aliased with another names
----------------
Example: import icici as i, aop as a , mathsinfo as m

=>Hence after importing all the variable names, Function names and class names by using "import
statement" , we must access variable names, Function names and class names w.r.t Module Names or alias
names.
Module Name.Variable Name
Module Name.Function Name
Module Name.Class Name
(OR)
Alias Name.Variable Name
Alias Name.Function Name
Alias Name.Class Name

=======================================
2) By using from.... import statement.
=======================================
=>Here "form" "import" are the key words
=>The purpose of from.... import statement is that " To refer or access the variable names, function names
and class names in current program directly without writing module name."
=> we can use from.... import statement in 3 ways.
-------------------
Syntax-1: from module name import Variable Names,Function Names, Class Names
------------------
=>This syntax imports the Variable Names,Function Names, Class Names of a module.

Example: from calendar import month


from aop import addop,subop
from mathinfo import pi,e
from icici import bname,addr

-----------------------------------------------------------------------------------------------------------
Syntax-2: from module name import Variable Names as alias name,Function Names as alias
name , Class Names as alias names.
-----------------------------------------------------------------------------------
=>This syntax imports the Variable Names,Function Names, Class Names of a module with alias Names

Example: from calendar import month as m


from aop import addop as a,subop as s, mulop as m
from mathinfo import pi as p ,e as k
from icici import bname as b, addr as a , simpleint as si
---------------------------------------------------------------------------------------------------------------------
Syntax-3: from module name import *
---------------
=>This syntax imports ALL Variable Names,Function Names, Class Names of a module.
=>This syntax is not recommmended to use bcoz it imports required Features of Module and also import
un-interrested features also imported and leads more main memory space.

Example: from calendar import *


from aop import *
from mathsinfo import *

=>Hence after importing all the variable names, Function names and class names by using "from ....import
statement" , we must access variable names, Function names and class names Directly without using
Module Names or alias names.

Variable Name
Function Name
Class Name

=>Hence with "import statement" we can give alias name for module names only but not for Variables
Names, Function Names and Class Names. Where as with "from ... import statement " we can give alias
names for Variables Names, Function Names and Class Names but not for Module Name.
Example:
--------------
#aop.py------File Name and acts as Module Name
def addop(a,b):
print("sum({},{})={}".format(a,b,a+b))

def subop(a,b):
print("sub({},{})={}".format(a,b,a-b))

-------------------------------------------------------------------
Example:
--------------
#cal.py
from calendar import month as k
while(True):
mon=int(input("Enter a Month (1-12):"))
if(mon in range(1,13)):
print(k(2022,mon))
break
print("\nInvalid Month:")

-----------------------------------------------------------------------
Example:
--------------
#icici.py--File Name and acts Module Name
bname="ICICI Banking"
addr="Ameerpet-HYD" # global variables

def simpleint(): # Function Definition


p=float(input("Enter Principle Amount:"))
t=float(input("Enter Time:"))
r=float(input("Enter Rate of Interest:"))
#cal si
si=(p*t*r)/100
totamt=p+si
print("-"*50)
print("\tPrinciple Amount:",p)
print("\tTime:",t)
print("\tRate of Interest:",r)
print("\tSimple Interest:",si)
print("\tTotal Amount to Pay:",totamt)
print("-"*50)
-----------------------------------------------------------------------
Example:
--------------
#MathsInfo.py---file name and acts as module name
PI=3.14
E=2.71 #Here PI and E are called Global variables

----------------------------------------------------------------------
Example:
--------------
#SE1.py
import MathsInfo
print("Val of PI=",MathsInfo.PI)
print("Val of E=",MathsInfo.E)
---------------------------------------------------------------------
Example:
--------------
#SE2.py
import aop
aop.addop(100,200)
aop.subop(-10,-20)

---------------------------------------------------------------------
Example:
--------------
#SE3.py
import icici
print("-"*50)
print("Bank Name:",icici.bname)
print("Bank Address:",icici.addr)
print("-"*50)
icici.simpleint()

Example:
--------------
#ApproachNo1.py
import icici # import module name--Syntax-1
print("-"*50)
print("Bank Name:",icici.bname)
print("Bank Address:",icici.addr)
print("-"*50)
icici.simpleint()

--------------------------------------------------------------------
Example:
--------------
#ApproachNo2.py
import icici ,aop,MathsInfo # import module name1, Module Name-2...--Syntax-2
print("-"*50)
print("Bank Name:",icici.bname)
print("Bank Address:",icici.addr)
print("-"*50)
icici.simpleint()
print("-"*50)
aop.addop(10,20)
aop.subop(100,200)
print("Val of PI=",MathsInfo.PI)
print("Val of E=",MathsInfo.E)
----------------------------------------------------------------------
Example:
--------------
#ApproachNo3.py
import icici as i # import module name1, as alias name Module Name-2 as alias name...--Syntax-3
import aop as a
import MathsInfo as m
print("-"*50)
print("Bank Name:",i.bname)
print("Bank Address:",i.addr)
print("-"*50)
i.simpleint()
print("-"*50)
a.addop(10,20)
a.subop(100,200)
print("Val of PI=",m.PI)
print("Val of E=",m.E)

Example:
--------------
#ApproachNo4.py
import icici as i ,aop as a, MathsInfo as m
print("-"*50)
print("Bank Name:",i.bname)
print("Bank Address:",i.addr)
print("-"*50)
i.simpleint()
print("-"*50)
a.addop(10,20)
a.subop(100,200)
print("Val of PI=",m.PI)
print("Val of E=",m.E)

--------------------------------------------------------------------
Example:
-------------
#ApproachNo5.py
from icici import bname,addr,simpleint
from aop import addop,subop
from MathsInfo import PI,E
print("-"*50)
print("Bank Name:",bname)
print("Bank Address:",addr)
print("-"*50)
simpleint()
print("-"*50)
addop(10,20)
subop(100,200)
print("Val of PI=",PI)
print("Val of E=",E)

----------------------------------------------------------------------
Example:
--------------
#ApproachNo6.py
from icici import bname as bn,addr as ad,simpleint as si
from aop import addop as ap,subop as sp
from MathsInfo import PI as p, E
print("-"*50)
print("Bank Name:",bn)
print("Bank Address:",ad)
print("-"*50)
si()
print("-"*50)
ap(10,20)
sp(100,200)
print("Val of PI=",p)
print("Val of E=",E)

-----------------------------------------------------------------------
Example:
--------------
#ApproachNo7.py
from icici import *
from aop import *
from MathsInfo import *
print("-"*50)
print("Bank Name:",bname)
print("Bank Address:",addr)
print("-"*50)
simpleint()
print("-"*50)
addop(10,20)
subop(100,200)
print("Val of PI=",PI)
print("Val of E=",E)

---------------------------------------------------------------------------------------------------------------------
Re-loading modules in Python
-----------------------------------------------------------------------------------------
==========================================
realoding a modules in Python
==========================================
=>To reaload a module in python , we use a pre-defined function called reload(), which is present in imp
module and it was deprecated in favour of importlib module.
=>Syntax:- imp.reload(module name)
(OR)
importlib.reload(module name) -----recommended
----------------------------------
=>Purpose / Situation:
-----------------------------------
=>reaload() reloads a previously imported module.
=>if we have edited the module source file by using an external editor and we want to use the changed values/
updated values / new version of previously loaded module then we use reload().
===================================X=======================================
Example:
--------------
#shares.py---file and treated as module name
def sharesinfo():
d={"Tech":19,"Pharma":11,"Auto":1,"Finance":00}
return d

#main program
#sharesdemo.py
import shares
import time
import importlib
def disp(d):
print("-"*50)
print("\tShare Name\tValue")
print("-"*50)
for sn,sv in d.items():
print("\t{}\t\t:{}".format(sn,sv))
else:
print("-"*50)
#main program
d=shares.sharesinfo()
disp(d)
time.sleep(15)
importlib.reload(shares) # relodaing previously imported module
d=shares.sharesinfo() # obtaining changed / new values of previously imported module
disp(d)
------------------------------------------------------------------------
Example:
---------------
#shares1.py---file name and acts as module name
def getsharesinfo():
d1={"IT":500,"Fin":400,"Auto":3500,"Pharma":3075}
return d1
#ShareDemo.py----main program
import shares1,time,importlib
def dispsharesinfo(d):
print("-"*50)
print("\tShare Name\tShare Value:")
print("-"*50)
for sn,sv in d.items():
print("\t{}\t\t{}".format(sn,sv))
print("-"*50)
-------------------------------------------------------------------------
Example:
-------------
#main program
d=shares1.getsharesinfo()
dispsharesinfo(d)
print("Line: 14--i am going to sleep for 15 secs")
time.sleep(15)
importlib.reload(shares1)
print("Line: 15--i am going out-of sleep after15 secs")
d=shares1.getsharesinfo()
dispsharesinfo(d)
print("Line: 20--i am going to sleep for 15 secs")
time.sleep(15)
importlib.reload(shares1)
print("Line: 23--i am going out-of sleep after 15 secs")
d=shares1.getsharesinfo()
dispsharesinfo(d)
------------------------------------------------------------------------------------------
Example:
--------------
#shares1.py---file name and acts as module name
def getsharesinfo():
d1={"IT":500,"Fin":400,"Auto":3500,"Pharma":3075}
return d1

-----------------------------------------------------------
Example:
--------------
#ShareDemo.py----main program
import shares1,time,importlib
def dispsharesinfo(d):
print("-"*50)
print("\tShare Name\tShare Value:")
print("-"*50)
for sn,sv in d.items():
print("\t{}\t\t{}".format(sn,sv))
print("-"*50)

#main program
d=shares1.getsharesinfo()
dispsharesinfo(d)
print("Line: 14--i am going to sleep for 15 secs")
time.sleep(15)
importlib.reload(shares1)
print("Line: 15--i am going out-of sleep after15 secs")
d=shares1.getsharesinfo()
dispsharesinfo(d)
print("Line: 20--i am going to sleep for 15 secs")
time.sleep(15)
importlib.reload(shares1)
print("Line: 23--i am going out-of sleep after 15 secs")
d=shares1.getsharesinfo()
dispsharesinfo(d)
-------------------------------------------------------------
Examples on modules:
-----------------------------------
#FigureMenu.py---file name and module name
def menu():
print("-"*50)
print("\tArea of Different Figures:")
print("-"*50)
print("\t1.Circle:")
print("\t2.Square:")
print("\t3.Rectangle:")
print("\t4.Triangle")
print("\t5.Exit")
print("-"*50)
---------------------------------------------------------
Example:
--------------
#FigureArea.py--file name and module name
def areacircle():
r=float(input("Enter Radious:"))
ac=3.14*r**2
print("Area of Circle:{}".format(ac))

def areasquare():
s=float(input("Enter Side:"))
sa=s**2
print("Area of Square:{}".format(sa))

def arearect():
l,b=float(input("Enter Length:")),float(input("Enter Breadth:"))
ra=l*b
print("Area of Rectangle:{}".format(ra))

def areatriangle():
b,h=float(input("Enter Base:")),float(input("Enter height:"))
ta=(1/2)*b*h
print("Area of Triangle:{}".format(ta))
print("----------------------OR-------------------------------------")
a,b,c=float(input("Enter First Side:")),float(input("Enter Second Side:")),float(input("Enter
Third Side:"))
s=(a+b+c)/2
ta=(s*(s-a)*(s-b)*(s-c))**0.5
print("Area of Triangle:{}".format(ta))
--------------------------------------------------------------
Example:
--------------
#FigureAreaDemo.py
from FigureMenu import menu
import sys
from FigureArea import areacircle,areasquare,areatriangle,arearect
while(True):
menu()
ch=int(input("Enter ur Choice:"))
match(ch):
case 1:
areacircle()
case 2:
areasquare()
case 3:
arearect()
case 4:
areatriangle()
case 5:
print("Thx for using this program")
sys.exit()
case _:
print("Ur selection of Operation is wrong--try again:")

--------------------------------------------------------------
Packages in Python programs:
-----------------------------------------------
=============================================
Package in Python
=============================================
=>The Function concept is used for Performing some operation and provides code re-usability within the
same program and unable to provide code re-usability across programs.

=>The Modules concept is a collection of Variables, Functions and classes and we can re-use the code
across the Programs provided Module name and main program present in same folder but unable to
provide code re-usability across the folders / drives / enviroments.

=>The Package Concept is a collection of Modules.


=>The purpose of Packages is that to provide code re-usability across the folders / drives / enviroments.

=>To deal with the package, we need to the learn the following.
a) create a package
b) re-use the package
--------------------------------------------------------------------------------------------------
a) create a package:
----------------------------
=>To create a package, we use the following steps.
i) create a Folder
ii) place / write an empty python file called __init__.py
iii) place / write the module(s) in the folder where is it considered as Package Name
Example:
--------------
bank <-----Package Name
-----------
__init__.py <----Empty Python File
simpleint.py <--- Module Name
aopmenu.py-----Module Name
aoperations.py---Module Name
runappl.py <--- Module Name
========================================================
b) re-use the package
---------------------------------
=>To the re-use the modules of the packages across the folders / drives / enviroments, we have to two
approaches. They are
i) By using sys module
ii) by using PYTHONPATH Environmental Variable Name
------------------------------------------------------------------------------------------
i) By using sys module:
-------------------------------------
Syntax:
----------- sys.path.append("Absolute Path of Package")

=>sys is pre-defined module


=>path is a pre-defined object / variable present in sys module
=>append() is pre-defined function present in path and is used for locating the package name of python(
specify the absolute path)

Example:

sys.path.append("E:\\KVR-PYTHON-7AM\\ACKAGES\\BANK")
(or)
sys.path.append("E:\KVR-PYTHON-7AM\ACKAGES\BANK")
(or)
sys.path.append("E:\KVR-PYTHON-7AM/ACKAGES/BANK")
-----------------------------------------------------------------------------------------------
ii) by using PYTHONPATH Environmental Variables:
------------------------------------------------------------------------
=>PYTHONPATH is one of the Enviromental Variable
=>Search for Enviromental Variable
Steps for setting :
------------------------------
Var name : PYTHONPATH
Var Value : E:\KVR-PYTHON-7AM\PACKAGES\BANK

The overall path


PYTHONPATH= E:\KVR-PYTHON-11AM\PACKAGES\BANK
-----------------------------------------------------------------------
=====================================
Packages in Python
=====================================
-----------------------------------------------
Index:
-----------------------------------------------
=>Purpose of Package
=>Steps for developing Package in Python
=>Re-Using the package
a) By using sys.path.append()
b) By using Environmental Variable ( PYTHONPATH)
=>Program Examples
-----------------------------------------------
IndexException Handling--Types of errors:
----------------------------------------------------------------------------------
===============================================
Exception Handling
===============================================
Index
----------
=>Purpose of Exception Handling
=>Types of Errors
a) Compile time Errors
b) Logical Errors
c) Runtime Errors
=>Types of Exceptions.
a) Pre-defined or Built-In Exceptions
b) Programmer or User or Custome Defined Exceptions
=>Keywords used in Exception Handling
a) try
b) except
c) else
d) finally
e) raise
=>Syntax for handling the Exceptions
=>Programming Examples
--------------------------------------------------------------------------------------------------
=>Development of Programmer or User or Custome Defined Exceptions
=>Programming Examples
---------------------------------------------------------------------------------------------------
ATM Case study
----------------------------
===============================================
Exception Handling
===============================================
=>The purpose of Exception Handling in python is that " To develop Robust(Strong)
Application."
=>In real time application development, to develop any project, we need to choose a programming
language. By using programming languages, we develop, compile and execute various programs. During
this process, we get 3 types of Errors. They are
1. Compile Time Errors
2. Logical Errors
3. Runtime Errors
------------------------------------
1. Compile Time Errors
------------------------------------
=>Compile Time Errors occurs durings Compilation Process(.py----->.pyc)
=>Compile Time Errors occurs due to Syntaxes are not followed
=>Compile Time Errors Solved by Programmers during Development Time.
-----------------------------------
2. Logical Errors
-----------------------------------
=>Logical Errors occurs durings Execution Time(.pyc----->machine code)
=>Logical Errors occurs due to wrong representation of logic
=>Logical Errors always gives wrong result
=>Logical Errors Solved by Programmers at Development time.
-------------------------------------------------------------------------------------------------------------
3. Runtime Errors
-------------------------------------------------------------------------------------------------------------
=>Runtime Errors occurs during Execution or Runt Time
=>Runtime Errors occurs due to Invalid or Wrong Input entered by Application Users(End
Users)
=>Runtime Errors must be addressed by Programmers in Projects for making the application
as Robust

==========================================================
Building Points for learning Exception Handling
==========================================================
1) When the application User Enters Invalid or Wrong input then we get Runtime Errors.
(Invalid Input----->Run Time Error)

2) By default Runtime Errors generates Technical Error Messages,which are are


understandable by programmers but not by End Users.

3) Definition of Exception: Runtime Error of Every Program is called Exception.


(Invalid Input----->Run Time Error---->Exception)

4) By default all exceptions generates Technical Error Messages,which are are


understandable by programmers but not by End Users. Industry is recommended to generates User-Freindly
Error Message by using of Exception Handling.

5) Definition of Exception Handling:- The process of Converting Technical Error Messages into
User-Freindly Error Messages is
called Exception Handling.

6) When the exception occurs then the following 3 things takes .


a) Program Execution Abnormally Terminated
b) PVM Comes out of program flow
c) By default PVM Generates Technical Error Messages.

7) To do Step-(a), Step-(b), Step-(c), Internally, PVM creates an object of appropriate exception


class.
8) In Python Programming, When an exception occurs then PVM creates an object of
appropriate exception class

9) Hence Every Exception makes the PVM to create an object appropriate exception class

10)Therefore Every Exception is considered as object.


===============================x======================================
Types of exceptions
Handling the exceptions---Syntax for handling the exceptions programs:
-----------------------------------------------------------------------------------------------
=========================================
Types of Exceptions
=========================================
=>In python programming we have two types of exceptions. They aare
1. Pre-defined or Built-In Exceptions
2. User OR Programmer or Custom defined exceptions
-------------------------------------------------
1. Pre-defined or Built-In Exceptions:
-------------------------------------------------
=>These exceptions devloped by Language Developers and avilable as a part of Python Software and
whose role is to deal with Universal Problems.
=>Some of the universal problems are
1. Divide by zero ( ZeroDivisionError )
2. Invalid Indexes (IndexError)
3. Module not existing ( ModuleNotFoundError)
4. Invalid Number Conversion ( ValueError )
5. Invalid Operations (TypeError)
6. Invalid Variable Name (NameError)....etc
----------------------------------------------------------------------------
2. User OR Programmer or Custom defined exceptions
----------------------------------------------------------------------------
=>These exceptions devloped by Python Programmers and avilable as a part of Python Project and whose
role is to deal with Common Problems.

=>Some of the common problems are


a) Attempting to enter invalid PIN in ATM based applications.
b) Attempting to withdraw More amount than existing balance in an Account.
c) Attempting to enter Invalid user name / password .
d) Attempting to enter invalid patterns
e) wrong OTPs during payment ...etc

================================================
Handling the Exceptions in Python Program
================================================
=>Handling the Exceptions in Python Program is nothing but converting the Technical Error Messages
into user-Frendly error messages.
=>For converting the Technical Error Messages into user-Frendly error messages, we have 5 keywords.
They are
a) try
b) except
c) else
d) finally
e) raise
-----------------------------------------------------
=>Syntax for handling the exceptions
-----------------------------------------------------
try:
Block of statements generates
Exceptions
except <exception-class-name-1>:
Block of statements generates
User-Friendly Error Messages.
except <exception-class-name-2>:
Block of statements generates
User-Friendly Error Messages.
-------------------------------------------
except <exception-class-name-n>:
Block of statements generates
User-Friendly Error Messages.
else:
Block of statements recommended to generates
Results.
finally:
Block of statements which will execute compulsorily.
Example:
--------------
#Program for accpting two integer values and find their division
#Div1.py
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
a=int(s1) #---------------------------Exception Generated statement
b=int(s2) #---------------------------Exception Generated statement
c=a/b #---------------------------Exception Generated statement
print("Div=",c)
---------------------------------------------------------------------------------------------------------------
Example:
--------------
#Program for accpting two integer values and find their division
#Div2.py
try:
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
a=int(s1) #---------------------------Exception Generated statement
b=int(s2) #---------------------------Exception Generated statement
c=a/b #---------------------------Exception Generated statement
except ZeroDivisionError:
print("\nDon't enter zero for Den...")
except ValueError:
print("\nDon't enter Strings, Symbols and alpha-numertics")
else:
print("val of a=",a)
print("val of b=",b)
print("Div=",c)
finally:
print("\ni am from finally block")
-------------------------------------------------------------------------------------------------------------
Explanation for the keywords of exception handling Various Forms of except block
programs
=======================================================
Explanation for the keywords of exception handling
=======================================================
=>As a part of exception handling, For converting the Technical Error Messages into user-Frendly error
messages, we have 5 keywords. They are
a) try
b) except
c) else
d) finally
e) raise
-------------------------------------------------------------------------------
a) try block
-------------------------------------------------------------------------------
=>It is the block, in which we write block of statements which are generating exceptions. In Otherwords,
what are all the statements generating exceptions, such type of statements must be written within try
block and try block is called exception monitering block.
=>When an exception occurs in try block then PVM comes out of try block and executes appropriate
except block.
=>After executing appropriate except block , PVM never goes to try block for executing rest of the
statements in try block.
=>Every try block must be immediately followed by except block.
=>Every try block must contain atleast one except block and recommnded to write multiple except blocks
for generating multiple user-friendly error messages.
-------------------------------------------------------------------------------
b) except block
-------------------------------------------------------------------------------
=>It is the block, In which we write block of statements which are generating User-Friendly error
messages. In Otherwords, except block supresses the Technical error messages and generates User-
Friendly Error Messages and hence except block is called exception processing block.
=>except block will execute when an exception occurs in try block.
=>Even we write multiple except blocks,when an exception occurs in try block then PVM executes
appropriate except block.
=>The place of writing except block is that after try block and before else block.
-------------------------------------------------------------------------------
c) else block
-------------------------------------------------------------------------------
=>It is the block, In which we write block of statements which are displaying Results.
=>else block will execute where there is no exception in try block.
=>Writing else bock is optional
=>The place of writing else block is that after except block and before finally block(if it present).
-------------------------------------------------------------------------------
d) finally block
-------------------------------------------------------------------------------
=>It is the block, In which we write block of statements which are relinquishing(close / release/ give-up/
clean-up) the resources (files/Database) which are obtainded in try block
=>finally block will execute compulsorily
=>Writing finally block is optional
=>The place of writing finally block is that after else block.
-----------------------------------------------------------------------
====================================================
Various Forms of except block
====================================================
=>We can use except block in different forms. They are
---------------------------------------------------------------
Form-1: except block with single exception (standard form)
---------------------------------------------------------------
try:
---------------
---------------
---------------
except <exception class name-1>:
---------------------------------
---------------------------------
except <exception class name-2>:
---------------------------------
---------------------------------
except <exception class name-n>:
---------------------------------
---------------------------------
Example Program: Div2.py
--------------------------------------------------------------------------------------------------------------------------------
Form-2: except block with multiple speficific exceptions--known as multi exception handling block.
--------------------------------------------------------------------------------------------------------------------------------
try:
---------------
---------------
---------------
except (<exception class name-1>,<exception class name-2>.......):
-------------------------------------
Block of statements generating
multiple User-Freindly Error Messages
for multiple exceptions
-----------------------------------------
Example Program: Div3.py
--------------------------------------------------------------------------------------------------------------------------------
Form-3: except block with speficific exception name with alias name
--------------------------------------------------------------------------------------------------------------------------------
try:
---------------
---------------
---------------
except <exception class name-1> as alias name:
---------------------------------
---------------------------------
=>In The alias name , we are capturing the message, which is occured due to exception occurence.
Example Program: Div4.py
--------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------
Form-4: except block without exception name and it is called default except block
--------------------------------------------------------------------------------------------------------------------------------
try:
---------------
---------------
---------------
except : # default except block
---------------------------------
---------------------------------
=>default except block must be written always at last otherwiose we get SyntaxError
Example Program: Div5.py
-------------------------
#Program for accpting two integer values and find their division
#Div2.py
try:
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
a=int(s1) #---------------------------Exception Generated statement
b=int(s2) #---------------------------Exception Generated statement
c=a/b #---------------------------Exception Generated statement
except (ZeroDivisionError:
print("\nDon't enter zero for Den...")
except ValueError:
print("\nDon't enter Strings, Symbols and alpha-numertics")
else:
print("val of a=",a)
print("val of b=",b)
print("Div=",c)
finally:
print("\ni am from finally block")
Example:
--------------
#Program for accpting two integer values and find their division
#Div3.py
try:
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
a=int(s1) #---------------------------Exception Generated statement
b=int(s2) #---------------------------Exception Generated statement
c=a/b #---------------------------Exception Generated statement
except (ZeroDivisionError, ValueError): # Multi exception handling block
print("\nDon't enter zero for Den...")
print("\nDon't enter Strings, Symbols and alpha-numertics")
else:
print("val of a=",a)
print("val of b=",b)
print("Div=",c)
finally:
print("\ni am from finally block")
----------------------------------------------------------------------------------------------------------------------
Example:
--------------
#Program for accpting two integer values and find their division
#Div4.py
try:
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
a=int(s1) #---------------------------Exception Generated statement
b=int(s2) #---------------------------Exception Generated statement
c=a/b #---------------------------Exception Generated statement
except ZeroDivisionError as z:
print(z)
except ValueError as v:
print(v)
else:
print("val of a=",a)
print("val of b=",b)
print("Div=",c)
finally:
print("\ni am from finally block")
----------------------------------------------------------------------------------------------------------------------
Example:
--------------
#Program for accpting two integer values and find their division
#Div5.py
try:
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
a=int(s1) #---------------------------Exception Generated statement
b=int(s2) #---------------------------Exception Generated statement
c=a/b #---------------------------Exception Generated statement
s="PYTHON"
print(s[10])
except ZeroDivisionError:
print("\nDon't enter zero for Den...")
except ValueError:
print("\nDon't enter Strings, Symbols and alpha-numertics")
except IndexError :
print("\nU Used Invalid Index--plz check:")
except: # Now it recommeded to write to handle future exceptions --default except block
print("\nsome thing went wrong")
else:
print("val of a=",a)
print("val of b=",b)
print("Div=",c)
finally:
print("\ni am from finally block")
-------------------------------------------------------------------------------------------------------------------------------
Development of Programmer or User or Custom Defined Exceptions
raise key word Programs
--------------------------------------------------------------------------------------------------------------------------

============================================================
Development of Programmer or User or Custome Defined Exceptions
==========================================================
=>These exception developed by Python Language Programmers and avialable in Python Project and
used by all Other python progarmmers for dealing with Common Problems.
=>Some of the Common Problems are

1) Attempting to enter Invalid PIN in ATM applications


2) Attempting to enter wrong User name and password
3) Attempting to withdraw more amount than existing bal in Account........etc

=>When the Application user enters Valid Input then we get Valid Output
=>When the application user enters Invalid Input then we get exception. When exception occurs then we
must create an object by using appropriate exception class. If the the exception class is Pre-defined then it
is Pre-defined Exception Class and if it is Programmer-Defined then it is Programmer-defined exception
class.
-----------------------------------------------------------------------------------------------------------
Steps for developing Programmer-Defined Exception class:
-----------------------------------------------------------------------------------------------------------
1. Define a Programmer-Defined Class

2. Programmer-Defined Class must Inherit from super class for all the exception whose name
is "Exception" or "BaseException" bcoz "Exception" or "BaseException" provides Exceptrion
handling Properties for abnormal Termination when application user enters invalid Input.

3. Save the above development of the code on some file name with an extension .py.
--------------------------------------------------------------------------------------------------------------------------------
Number of Phases required for developing programmer-defined exception based applicatrions.

Phase-1: Development of Exception classes


Phase-2: Development of Common Functions which will hit the exceptions
Phase-3: Handling the Exceptions
-----------------------------------------------------------------------------------------------
Example:
--------------------
Phase-1: Development of Exception classes---Example

#kvr.py-----File Name and acts as module name


class KvrDivisionError(Exception):pass
Example:
--------------------
Phase-2: Development of Common Functions which will hit the exceptions

#division.py-----file name and module name


from kvr import KvrDivisionError
def division(a,b): # Development of Common Function--Phase-2
if(b==0):
raise KvrDivisionError # Hitting or raising or generating

Programmer-defined exception
else:
return(a/b)

-----------------------------------------------------------------------------------------------------------------
Example:
--------------------
Phase-3: Handling the Exceptions :

#DivDemo.py
from division import division
from kvr import KvrDivisionError
try:
a=int(input("Enter First Value:"))
b=int(input("Enter Second Value:"))
res=division(a,b)
except KvrDivisionError:
print("\ndon't enter zero for den...")
except ValueError:
print("\nDon't enter strs, symbols and alpha-numerics")
else:
print("Div=",res)
finally:
print("i am from finally block")
-----------------------------------------------------------------------------------------------------------------------------

=================================================
raise key word
=================================================
=>raise keyword is used for hitting / raising / generating the exception provided some condition must be
satisfied.
=>raise keyword always used inside of Function Definition only.
=>PVM uses raise keyword implicitly for hitting pre-defined Exception where as Programmer makes the
PVM to use use raise keyword explicitly for Hitting or Generating Programmer-defined Exceptions.

=>Syntax:- if (Test Cond):


raise <exception-class-name>

=>Syntax:- def functionname(list of formal parms if any):


-----------------------------------------------------
-----------------------------------------------------
if (Test Cond):
raise <exception-class-name>
--------------------------------------------------------

Examples:
-------------------
from kvr import KvrDivisionError
def division(a,b):
if(b==0):
raise KvrDivisionError
else:
return (a/b)
--------------------------------------------------------------------------------------------------------------------
Example:
--------------------
#Program for handling the exceptions when we are cal division of two numbers.
#DivDemo.py
from division import division
from kvr import KvrDivisionError
try:
a=int(input("Enter First Value:"))
b=int(input("Enter Second Value:"))
res=division(a,b)
except KvrDivisionError:
print("\ndon't enter zero for den...")
except ValueError:
print("\nDon't enter strs, symbols and alpha-numerics")
else:
print("Div=",res)
finally:
print("i am from finally block")

----------------------------------------------------------------------------------------------------------------------
Example:
--------------------
#Program cal division of two numbers and hit or raise the exceptions if required
#division.py-----file name and module name
from kvr import KvrDivisionError
def division(a,b): # Development of Common Function--Phase-2
if(b==0):
raise KvrDivisionError # Hitting or raising or generating Programmer-defined
exception
else:
return(a/b)
-----------------------------------------------------------------------------------------------------------------------
Example:
--------------------
#Program developing programmer-defined exception class and it should work like ZeroDivisionError.
# HINT----Inplace of ZeroDivisionError , we are taking KvrDivisionError.
#kvr.py-----File Name and acts as module name
class KvrDivisionError(Exception):pass # Development of Programmer-defined exception class Phase-1
--------------------------------------------------------------------
#MulExcept.py--File Name and Module Name

class NegNumberError(Exception):pass

class ZeroInputError(BaseException):pass

-----------------------------------------------------------------------------------------------------------------------
Example:
--------------------
#MulTable.py--File Name and module name
from MulExcept import NegNumberError,ZeroInputError
def table():
n=int(input("Enter a Number:")) # Implcitly PVM raises ValueError
if(n<0):
raise NegNumberError
elif(n==0):
raise ZeroInputError
else:
print("-"*50)
print("Mul Table for:{}".format(n))
print("-"*50)
for i in range(1,11):
print("\t{} x {} = {}".format(n,i,n*i))
print("-"*50)
-----------------------------------------------------------------------------------------------------------------------------
Example:
------------------------
#MulTableDemo.py
from MulTable import table
from MulExcept import NegNumberError,ZeroInputError
try:
table()
except NegNumberError:
print("\nDon't enter Negative Number ")
except ZeroInputError:
print("\nDon't enter zero :")
except ValueError:
print("\nDon't enter strs, symbols and alpha-numerics")
finally:
print("I am from finally block")
--------------------------------------------------------------------------------------------------------------------------------
-----------------
ATM Project:
-----------------
Example:
-------------------
#AtmMenu.py--File Name and acts as module name
def menu():
print("-"*50)
print("\tATM Operation(Funds Transfer):")
print("-"*50)
print("\t1.Deposit")
print("\t2.Withdraw")
print("\t3.BalEnq")
print("\t4.Exit")
print("-"*50)
---------------------------------------------------------------------------------------
Example:
-------------------
#AtmExcept.py---file name and acts as module name
class DepositError(Exception):pass

class WithdrawError(BaseException):pass

class InSuffFundError(Exception):pass
-----------------------------------------------------------------------------------------
Example:
-----------------
#AtmOperations.py---file name and acts as module name
from AtmExcept import DepositError,WithdrawError,InSuffFundError
bal=500.00 # Global variable
def deposit():
damt=float(input("Enter How much amount u want to deposit:")) # ValueError
if(damt<=0):
raise DepositError
else:
global bal
bal=bal+damt
print("Ur Account xxxxxxxx123 Credited with INR:{}".format(damt))
print("Now Ur Account balance INR:{}".format(bal))

def withdraw():
global bal
wamt=float(input("Enter How much amount u want to Withdraw:")) # ValueError
if(wamt<=0):
raise WithdrawError
elif((wamt+500)>bal):
raise InSuffFundError
else:
bal=bal-wamt
print("Ur Account xxxxxxxx123 Debited with INR:{}".format(wamt))
print("Now Ur Account balance INR:{}".format(bal))

def balenq():
print("Account balance INR:{}".format(bal))

----------------------------------------------------------------------------------------
Example:
-------------------
#ATMDemo.py---file name and acts as module name
from AtmMenu import menu
from AtmOperations import deposit,withdraw,balenq
from AtmExcept import DepositError,WithdrawError,InSuffFundError
import sys
def atmproject():
while(True):
try:
menu()
ch=int(input("Enter ur Choice:"))
match(ch):
case 1:
try:
deposit()
except ValueError:
print("Don't enter strs, symbols and alph-
numerics for deposit Operation:")
except DepositError:
print("Don't try deposit -ve and zero
values:")
case 2:
try:
withdraw()
except ValueError:
print("Don't enter strs, symbols and alph-
numerics for Withdraw Operation:")
except WithdrawError:
print("Don't try withdraw -ve and zero
values:")
except InSuffFundError:
print("U don't have suff Funds in ur
Account--Read Python Notes:")
case 3:
balenq()
case 4:
print("Thx for using this program:")
sys.exit()
case _:
print("Ur Selection of Operation is wrong-try again")
except ValueError:
print("Don't enter strs, symbols and alph-numerics for ur choice:")

---------------------------------------------------
Example:
--------------------
#runatmproject.py
import sys
sys.path.append("E:\\KVR-PYTHON-9AM\\ATM-PACK")
from ATMDemo import atmproject as atm
import getpass,random
cnt=0
while(True):
rpwd=random.randint(1000,10000)
print("Ur Pin is :",rpwd)
psswd=getpass.getpass(prompt="Enter Ur Pin:")
if(psswd==str(rpwd)):
break
print("Invalid Inpin Try again:")
cnt=cnt+1
if(cnt==3):
print("Ur are blocked--Contact Banch manager:")
sys.exit()

atm()
-----------------------------------------------------
Index of Files
Types of Applications Introduction to files:
-------------------------------------------------------------
==============================================
Files in Python
==============================================
Index
----------
=>Purpose of Files
=>Types of Applications
a) Non-Persistant Applications
b) Persistant Applications
=>Definition of File
=>What is meant by Stream
=>Types of Files
a) Text Files
b) Binary Files
=>Operations on Files
a) Write Operation
b) Read Operration
=>File Opening Modes
1) r
2) w
3) a
4) r+
5) w+
6) a+
7) x
=>Syntax for Opening the files
a) By using open()
b) By using " with open() as "
=>Programming Examples
-------------------------------------------------------------------
=>Pickling(Object Serialization) and Un-Pickling((Object De-Serialization) in Python
=>pickle module and implementation
=>Programming Examples
-------------------------------------------------------------------
=>Working with CSV Files
=>Programming CSV Files

---------------------------------------------------------------------
=>OS Module
------------------------------------------------------------
===============================================
Files in Python
(OR)
Stream Handling in Python
===============================================
=>The purpose of Files concept is that " To store the data Permanently ".
=>The process of storing the data permanently is known as "Persistentcy".
--------------------------------------------------------------------------------------------------------
=->In The context of files, we can develop two types of applications. They are
a) Non-persistency Applications
b) Persistent Applications.
=>In Non-persistency Application development, we accept the data from Key board,stores in main memory in
the form of objects, process the data and shown the result on the console .
=>The results which are available in the main memory are Temporary.

=>In persistent Application development, we accept the data from Key board,stores in main memory in the form
of objects, process the data and whose results are stored permanently.
=>To store the result of any programming language permanently, we have two approaches. they are
a) By using Files
b) By using data base softwares.
=>Note that if we write any python programming by using Files and Database softwares then such type of
applications are comes under the example Persistent Applications.
==========================================================================

============================================
Data Persistenecy by Files of Python
============================================
-------------------
Def. of File:
-------------------
=>A File is a collection of Records.
=>Files Resides in Secondary Memory.
=>Technically, File Name is a named location in Secondary Memory.
-----------------------------------------------------
=>All the objects data of main memory becomes records in File of Secondary memory and records of file
of secondary memory becomes the objects in main memory.

----------------------------------------------------
Def. of Stream:
----------------------------------------------------
=>The Flow of Data between object(s) of Main Memory and Files of Seconday memory is called
Stream.
----------------------------------------------------------------
==============================================
Operations on Files
==============================================
=>On the files, we can perform Two Types of Operations. They are
1) Write Operation.
2) Read Operation.
1) Write Operation:
-----------------------------
=>The purpose of write operation is that " To transfer or save the object data of main memory as record in
the file of secondary memory".
=>Steps:
1) Choose the File Name
2) Open the File Name in Write Mode
3) Perform cycle of Write Operations.
=>While we performing write operations, we get the following exceptions.
a) IOError
b) OSError
c) FileExistError
------------------------------
2) Read Operation:
------------------------------
=>The purpose of read operation is that " To transfer or read the record from file of secondary memory
into the object of main memory".
=>Steps
a) Choose the file name
b) Open the file name in Read Mode
c) Perform cycle of read operations.
=>While we performing read operations, we get the following exceptions.
a) FileNotFoundError
b) EOFError

=======================================================
Persistent Application development by using Files in Python
======================================================
=>File Concept is one language Independent where we can store the data permanently.
=>The communication between Python Program and Files is comes under development of Persistant
Application.
--------------------------------
=>Definition of File:
--------------------------------
=> A File is a collection of Records
=>A File Name is one of the Named Location in Secondary Memory.
=>Files of any programming resides in Secondary Memory.
=>In Files Programming, Every Object Data becomes a record in a file of secondary memory and every
record of file of sedondary memory will become an object in main memory.
--------------------------------------------------------------------------------------------------------------------------------
Definition of Steram:
------------------------------
=>The flow of data between main memory and file of secondary memory is called Stream.
-----------------------------------------------------------------------

================================
Types of Files
================================
=>In Python Programming, we have two types of Files. They are
a) Text Files
b) Binary Files

1) Text File:
--------------------
=>A Text File always contains Alphabets, Digits and Special Symbols.
=>Text Files always denoted by a letter "t"
=>The default file in python is text file.
-------------------------------------------------------
Examples: .py .java .c .cpp .txt .doc....etc
-----------------------------------------------------------------------------------------------------
2) Binary File:
--------------------
=>A BinaryFile always contains Data in Binary Format ( Pixles)
=>Binary Files always denoted by a letter "b"

Examples: images (.jpg, .jpeg, .png, .gif)


audio and video files
PDF documents
------------------------------------------------------------

File Opening Modes Syntax for opening the files:


---------------------------------------------------------------------
===============================================
File Opening Modes
===============================================
=>The purpose of File Opening Modes is that " In which mode the files are opened."
=>To perform any type of operation on the files, the files must be opened in appropriate mode.
=>In Python Programming, we have 8 file opening modes. they are
-------------------------------------------------------------------------------------------------
1. r
-------------------------------------------------------------------------------------------------
=>This mode is used for Opening the file Name in Read Mode
=>It is one of the default file mode
=>If we open the file name in "r" mode and if the file does not exist then we get
FileNotFoundError.
-------------------------------------------------------------------------------------------------
2. w
-------------------------------------------------------------------------------------------------
=>This mode is used creating the file and opening the file in write mode always.
=>When we open NEW FILE in "w" Mode then new file will be opened in write mode and data written
form begining of the file always.
=>When we open EXISTING FILE in "w" Mode then existing data of the existing file OVERLAPPED
with new Data.
-------------------------------------------------------------------------------------------------
3. a
-------------------------------------------------------------------------------------------------
=>This mode is used creating the file and opening the file in write mode always.
=>When we open NEW FILE in "a" Mode then new file will be opened in write mode and data
written form begining of the file always.
=>When we open EXISTING FILE in "a" Mode then existing data of the existing file APPENDED
with new Data.
-------------------------------------------------------------------------------------------------
4. r+
-------------------------------------------------------------------------------------------------
=>This mode is also used for Opening the file in Read Mode and Performs Read Operation.
=>After reading the data from file and later we can also Perform Write Operation.
=>When we open the file in "r+" mode and if the file does not exist then we get
FileNotFoundError.
-------------------------------------------------------------------------------------------------
5. w+
-------------------------------------------------------------------------------------------------
=>This mode is used for Opening the file in write mode and Performs Write Operation always and later
Additonally we can perform Read Operations also.
=>When we open NEW FILE in "w+" Mode the new file will be opened in write mode and data written
form begining of the file always and later we can read the data also.
=>When we open EXISTING FILE in "w+" Mode then existing data of the existing file OVERLAPPED
with new Data and later we can read the data also.
-------------------------------------------------------------------------------------------------
6. a+
-------------------------------------------------------------------------------------------------
=>This mode is used creating the file and opening the file in write mode always and performs
write operation First and later additionally we can perform read Operation also.
=>When we open NEW FILE in "a+" Mode the new file will be opened in write mode and data
written form the begining of the file always and later we can perform read operation.
=>When we open EXISTING FILE in "a+" Mode then existing data of the existing file
APPENDED with new Data and later we can perform read operation.
------------------------------------------------------------------------------------------------------------
7. x
-----------------------------------------------------------------------------------------------------------
=>This mode is used for creating the new file and opening that file in Write Mode eXclusively only once.
=>If we open open exitsing file in "x" mode then PVM generates FileExistError.
-------------------------------------------------------------------------------------------------------------------------------
8. x+
-------------------------------------------------------------------------------------------------------------------------------
=>This mode is used for creating the new file and opening that file in Write Mode eXclusively
only once and after performing Write Operation and later we can also perform Read
Operations also.
=>If we open open exitsing file in "x+" mode then PVM generates FileExistError.
-----------------------------------------------------------------------
==============================================
Syntax for Opening the files
==============================================
=>In Python Programming, we have two syntaxes for opening the files. They are
a) By using open()
b) By using " with open() as "
------------------------------------
a) By using open()
------------------------------------
=>Syntax:- varname=open("FileName","File Mode")
----------------------
Explanation:
----------------------
=>varname represents an object of type <class,"TextIOWrapper"> and it is called File Pointer( is nothing
but varname points to the file).
=>open() of the pre-defined function present in "builtins" and it is used for opening the
specified File in specified File Mode.
=>"FileName" represents name of the file specified by Programmer
=>"FileMode" represents any file available file opening modes(r,w,a,r+,w+,a+,x)
=>When we open any file with Open() then we must close that file manually by using close().In
otherwords Auto-Closable Property not maintained.
--------------------------------------------------------------------------------------------------------------------------
a) By using "with open() as "
--------------------------------------------------------------------------------------------------------------------------
Syntax:
------------
with open( "File Name","File Mode") as <varname>:
-------------------------------------------------------------
-------------------------------------------------------------
File related Operation stmts
-------------------------------------------------------------
-------------------------------------------------------------

---------------------------------------------------------------
Block of statements
---------------------------------------------------------------

Explanation:
-------------------
=> 'with' and 'as' are the key words
=> open() of the pre-defined function present in "builtins" and it is used for opening the
specified File in specified File Mode.
=>varname represents an object of type <class,"TextIOWrapper"> and it is called File Pointer( is nothing
but varname points to the file).
=>"FileName" represents name of the file specified by Programmer
=>"FileMode" represents any file available file opening modes(r,w,a,r+,w+,a+,x)
=>The Advantage of "with open() as " approach is that Auto-Closing the File. In otherwords Programmer
need not to close the file manually.
==================================X==================================
Example:
-----------
#Program for opening the file in r mode
#FileOpenEx1.py
try:
fp=open("Stud.data","r")
except FileNotFoundError:
print("File does not Exist:")
else:
print("File Opened in Read Mode Successfully:")
print("Type of fp=",type(fp))
print("Name of the file=", fp.name)
print("File Opening Mode=",fp.mode)
print("Is this file readable=",fp.readable() )
print("Is this file writeable=",fp.writable() )
print("Is this file closed=",fp.closed )
finally:
print("i am fom finally block")
fp.close() # Closing the file manually
print("Is this file closed in finally =",fp.closed )
------------------------------------------------------------------------------------------------------------------
Examples:
----------------------
#Program opening the file w mode
#FileOpenEx2.py
fp=open("stud.data","w")
print("File created and opened in wrote mode successfully:")
print("--------------------------------------------------")
print("Type of fp=",type(fp))
print("Name of the file=", fp.name)
print("File Opening Mode=",fp.mode)
print("Is this file readable=",fp.readable() )
print("Is this file writeable=",fp.writable() )
print("Is this file closed=",fp.closed )
fp.close() # Closing the file manually
print("Is this file closed after close()=",fp.closed )

--------------------------------------------------------------------------------------------------------------------------
Examples:
----------------------
#Program opening the file w mode " with open() as "
#FileOpenEx3.py
with open("emp.data","w") as fp:
print("--------------------------------------------------")
print("PVM is in with open() as indendation block")
print("File created and opened in wrote mode successfully:")
print("--------------------------------------------------")
print("Type of fp=",type(fp))
print("Name of the file=", fp.name)
print("File Opening Mode=",fp.mode)
print("Is this file readable=",fp.readable() )
print("Is this file writeable=",fp.writable() )
print("Is this file closed=",fp.closed )
print("--------------------------------------------------")
print("\nPVM is out-of 'with open() as' indendation block:")
print("Is this file closed=",fp.closed )
------------------------------------------------------------------------------------------------------------------------
Examples:
----------------------
#Program opening the file a mode " with open() as "
#FileOpenEx4.py
with open("emp.data","a+") as fp:
print("--------------------------------------------------")
print("PVM is in with open() as indendation block")
print("File created and opened in wrote mode successfully:")
print("--------------------------------------------------")
print("Type of fp=",type(fp))
print("Name of the file=", fp.name)
print("File Opening Mode=",fp.mode)
print("Is this file readable=",fp.readable() )
print("Is this file writeable=",fp.writable() )
print("Is this file closed=",fp.closed )
print("--------------------------------------------------")
print("\nPVM is out-of 'with open() as' indendation block:")
print("Is this file closed=",fp.closed )
-----------------------------------------------------------------------------------------------------------------------
Examples:
----------------------
#Program opening the file x mode " with open() as "
#FileOpenEx5.py
try:
with open("kvr.data","x") as fp:
print("--------------------------------------------------")
print("PVM is in with open() as indendation block")
print("File created and opened in wrote mode successfully:")
print("--------------------------------------------------")
print("Type of fp=",type(fp))
print("Name of the file=", fp.name)
print("File Opening Mode=",fp.mode)
print("Is this file readable=",fp.readable() )
print("Is this file writeable=",fp.writable() )
print("Is this file closed=",fp.closed )
print("--------------------------------------------------")
print("\nPVM is out-of 'with open() as' indendation block:")
print("Is this file closed=",fp.closed )
except FileExistsError:
print("File Name already exist:")
--------------------------------------------------------------------------------------------------------------------
Examples:
----------------------
#Program opening the file x mode " with open() as "
#FileOpenEx6.py
try:
with open("kvr1.data","x+") as fp:
print("--------------------------------------------------")
print("PVM is in with open() as indendation block")
print("File created and opened in wrote mode successfully:")
print("--------------------------------------------------")
print("Type of fp=",type(fp))
print("Name of the file=", fp.name)
print("File Opening Mode=",fp.mode)
print("Is this file readable=",fp.readable() )
print("Is this file writeable=",fp.writable() )
print("Is this file closed=",fp.closed )
print("--------------------------------------------------")
print("\nPVM is out-of 'with open() as' indendation block:")
print("Is this file closed=",fp.closed )
except FileExistsError:
print("File Name already exist:")
--------------------------------------------------------------------------------------------------------------------
Examples:
----------------------
#Program opening the file x mode " with open() as "
#FileOpenEx7.py
try:
with open("kvr1.data","x") as fp:
print("------------------------------------------------")
print("PVM is in with open() as indendation block")
print("File created and opened in wrote mode successfully:")
print("------------------------------------------------")
print("Type of fp=",type(fp))
print("Name of the file=", fp.name)
print("File Opening Mode=",fp.mode)
print("Is this file readable=",fp.readable() )
print("Is this file writeable=",fp.writable() )
print("Is this file closed=",fp.closed )
print("--------------------------------------------------")
print("\nPVM is out-of 'with open() as' indendation block:")
print("Is this file closed=",fp.closed )
except FileExistsError:
print("File Name already exist:")
-----------------------------------------------------------------------------------------------------------------------
Writing the data files programs:
---------------------------------------------------------------------------------------------------------
================================================
Writing the data to the file
================================================
=>To write the data to the file, we have two pre-defined functions. They are
1) write()
2) writelines()
-------------------------------------------------------------------------------------------------------------
1) write()
-------------------------------------------------------------------------------------------------------------
=>This function is used for writing any type of data to the file in the form of str.
=>If we want to write Numerical data to the file then we convert numerical data into str type.
=>Syntax: - filepointer.write(strdata)

Examples
-----------------
#DataWriteEx1.py
with open("addr1.data","a") as fp:
fp.write("Mc Kinney\n")
fp.write("FNO 112 North Side\n")
fp.write("Pandas Software Foundation\n")
fp.write("Fin Lands-56\n")
print("Data Written to the file:")
----------------------------------------------------------------------
2) writelines()
-----------------------------------------------------------------------
=>This function is used for writing any type of Iterable Object data to the file in the form of str.
=>Syntax: - filepointer.writelines(Iterable Object)

Examples:
----------------------
#DataWriteEx2.py
d={10:"Python",20:"Java",30:"Data Sci"}
fp=open("add2.data","a")
fp.writelines(str(d)+"\n")
print("Data Written to the file")
-----------------------------------------------------------------------------------------------------------------
Examples:
----------------------
#Program for demonstrating how to write the data to the file
#DataWriteEx1.py
with open("addr1.data","a") as fp:
fp.write("Mc Kinney\n")
fp.write("FNO 112 North Side\n")
fp.write("Pandas Software Foundation\n")
fp.write("Fin Lands-56\n")
print("Data Written to the file:")
------------------------------------------------------------------------------------------------------------
Examples:
----------------------
#Program for writring the Itera ble object data to the file
#DataWriteEx2.py
d={10:"Python",20:"Java",30:"Data Sci"}
fp=open("add2.data","a")
fp.writelines(str(d)+"\n")
print("Data Written to the file")

-------------------------------------------------------------------------------------------------------------------------
Examples:
----------------------
#write a python programm which will read the data dynamically from keyboard and write it to the file
#DynamicWriteEx.py
with open("hyd.info","a") as fp:
print("Enter the data and press (stop) to terminate the program:")
print("-"*50)
while(True):
data=input()
if(data=="stop"):
break
else:
fp.write(data+"\n")
print("\nData written to the file--verify")

---------------------------------------------------------------------
Reading the data from the files Programs:
--------------------------------------------------------------------
================================================
Reading the Data from the File
================================================
=>To read the data from the file, we have 4 pre-defined functions. They are
1) read()
2) read(no.of chars)
3) readline()
4) readlines()
----------------------------------------------------------------------
1) read()
----------------------------------------------------------------------
=>This Function is used for reading ENTIRE DATA of the file in the form of str.
=>Syntax:- strobj=filepointer.read()
----------------------
Examples:-
---------------------
#FileReadEx1.py
filename=input("Enter any File Name for displaying its content:")
try:
with open(filename,"r") as fp:
filedata=fp.read()
print("-"*50)
print("Content of File:")
print("-"*50)
print(filedata)
print("-"*50)
except FileNotFoundError:
print("{}: does not exist:".format(filename))

-----------------------------------------------------------------------
2) read(no.of chars)
-----------------------------------------------------------------------
=>This Function is used for reading Specified Number of Chars from the file in the form of str.
=>Syntax:- strobj=filepointer.read(No. of chars)
-----------------
Examples:
-----------------
#write a python program reading certain chars from given file---tell() seek()
#FileReadEx2.py
try:
with open("addr1.data","r") as fp:
print("Initial Position of fp=",fp.tell())# 0
filedata=fp.read(6)
print("No. of chars=",filedata) # Travis
print("Now Position of fp=",fp.tell())# 6
filedata=fp.read(8)
print("No. of chars=",filedata) #
print("Now Position of fp=",fp.tell())# 14
filedata=fp.read(50)
print("No. of chars=",filedata) #
print("Now Position of fp=",fp.tell())# 67
filedata=fp.read()
print("\nNo. of chars=",filedata) #
print("Now Position of fp=",fp.tell())# 67
#re-set to the Initial Index
fp.seek(0)
print("\nNow Position of fp=",fp.tell())# 0
filedata=fp.read()
print("File Data=",filedata)
except FileNotFoundError:
print("{}: does not exist:".format(filename))
------------------------------------------------------------------------------------------------------------------------------
3) readline()
------------------------------------------------------------------------------------------------------------------------------
=>This Function is used for reading One Line at a time from the file in the form of str.
=>Syntax:- strobj=filepointer.readline()
---------------
Examples:
---------------
#write a python program reading one line at a time from File
#FileReadEx3.py
try:
with open("addr1.data","r") as fp:
filedata=fp.readline()
print(filedata)
filedata=fp.readline()
print(filedata)
filedata=fp.readline()
print(filedata)
except FileNotFoundError:
print("{}: does not exist:".format(filename))
------------------------------------------------------------------------------------------------------------------------------
4) readlines()
------------------------------------------------------------------------------------------------------------------------------
=>This Function is used for reading ALL Lines at a time from the file in the form of list.
=>Syntax:- strobj=filepointer.readline()
------------------
Examples:
------------------
#write a python program reading all the lines of a file
#FileReadEx4.py
try:
with open("addr1.data","r") as fp:
filedata=fp.readlines()
for line in filedata:
print(line,end="")
except FileNotFoundError:
print("{}: does not exist:".format(filename))
-----------------------------------------------------------------------

Example:
----------
#write a python program which will read the content of any file and display on the console
#FileReadEx1.py
filename=input("Enter any File Name for displaying its content:")
try:
with open(filename,"r") as fp:
filedata=fp.read()
print("-"*50)
print("Content of File:")
print("-"*50)
print(filedata)
print("-"*50)
except FileNotFoundError:
print("{}: does not exist:".format(filename))
---------------------------------------------------------------------------------------------------------------
Examples:
----------------------
#write a python program reading certain chars from given file---tell() seek()
#FileReadEx2.py
try:
with open("addr1.data","r") as fp:
print("Initial Position of fp=",fp.tell())# 0
filedata=fp.read(6)
print("No. of chars=",filedata) # Travis
print("Now Position of fp=",fp.tell())# 6
filedata=fp.read(8)
print("No. of chars=",filedata) #
print("Now Position of fp=",fp.tell())# 14
filedata=fp.read(50)
print("No. of chars=",filedata) #
print("Now Position of fp=",fp.tell())# 67
filedata=fp.read()
print("\nNo. of chars=",filedata) #
print("Now Position of fp=",fp.tell())# 67
#re-set to the Initial Index
fp.seek(0)
print("\nNow Position of fp=",fp.tell())# 0
filedata=fp.read()
print("File Data=",filedata)
except FileNotFoundError:
print("{}: does not exist:".format(filename))
-------------------------------------------------------------------------------------------------------
Examples:
----------------------
#write a python program reading one line at a time from File
#FileReadEx3.py
try:
with open("addr1.data","r") as fp:
filedata=fp.readline()
print(filedata)
filedata=fp.readline()
print(filedata)
filedata=fp.readline()
print(filedata)
except FileNotFoundError:
print("{}: does not exist:".format(filename))
----------------------------------------------------------------------
Examples:
----------------------
#write a python program reading all the lines of a file
#FileReadEx4.py
try:
with open("addr1.data","r") as fp:
filedata=fp.readlines()
for line in filedata:
print(line,end="")
except FileNotFoundError:
print("{}: does not exist:".format(filename))
-----------------------------------------------------------------------
Additional Programs on Files:
----------------------------------------------
Examples:
----------------------
#Program for copying the content of one file into another file
#FileCopy.py
sfile=input("Enter Source File:")
try:
with open(sfile,"r") as rp:
dfile=input("Enter Destination File:")
with open(dfile,"a") as wp:
#read the data from source file
sfiledata=rp.read()
#write the source file data to destination file
wp.write(sfiledata)
print("\nFile Copied--verify")
except FileNotFoundError:
print("Source File does not exist:")

-----------------------------------------------------------------------------------------------------------
Examples:
----------------------
#Program for copying the image
#ImageCopy.py
sfile=input("Enter Source File:")
try:
with open(sfile,"rb") as rp:
dfile=input("Enter Destination File:")
with open(dfile,"ab") as wp:
#read the data from source file
sfiledata=rp.read()
#write the source file data to destination file
wp.write(sfiledata)
print("\nImage Copied--verify")
except FileNotFoundError:
print("Source File does not exist:")
----------------------------------------------------------------------------------------------------------------
Examples:
----------------------
#write a python program which will accept any file name and find no.of lines, no.of words and no
characters
#CountFileInfo.py
sfile=input("Enter Source File:")
try:
with open(sfile,"r") as rp:
nl=0
nw=0
nc=0
lines=rp.readlines()
for line in lines:
print(line,end="")
nl=nl+1
nw=nw+len(line.split())
nc=nc+len(line)
else:
print("-"*50)
print("Number of Lines=",nl)
print("Number of Words=",nw)
print("Number of Chars=",nc)
print("-"*50)

except FileNotFoundError:
print("Source File does not exist:")
---------------------------------------------------------------------------------------------------------------
Pickling and Un-Pickling
(OR)
Object Serialization or Object De-Serialization Programs
-------------------------------------------------------------------------------------------------------------
=================================================
Pickling and Un-Pickling
(OR)
Object Serialization or Object De-Serialization
=================================================
---------------------------------------------
Pickling ( Object Serialization):
--------------------------------------------
=>Let us assume there exist an object which contains multiple values. To
save or write object data of main memory into the file of secondary memory by using write() and
writelines() , they transfers the values in the form of value by value and it is one of the time consuming
process( multiple write operations).
=>To Overcome this time consuming process, we must use the concept of Pickling.
=>The advantage of pickling concept is that with single write operation , we can
save or write entire object data of main memory into the file of secondary memory.

Definition of Pickling:
---------------------------------
=>The Process saving or transfering entire object content of main memory into the file of secondary
memory by performing single write operation is called Pickling.
=>Pickling concept participates in Write Operations.
-----------------------------------------------------------
Steps for implementing Pickling Concept:
-----------------------------------------------------------
=>import pickle module, here pickle is one of the pre-defined module
=>Choose the file name and open it into write mode.
=>Create an object with collection of values (Iterable object)
=>use the dump() of pickle module. dump() save the content of any object into the
file with single write operation.
Syntax: pickle.dump(object , filepointer)
=>NOTE That pickling concept always takes the file in Binary Format.
--------------------------------------------------------------------------------------------------------------
Un-Pickling (Object De-Serialization)
--------------------------------------------------------
=>Let us assume there exists a record with multiple values in a file of secondary memory. To read or
trasfer the entire record content from file of secondary memory, if we use read(), read(no.of chars),
readline() and readlines() then they read record values in the form of value by value and it is one of the
time consuming process( multiple read operations).
=>To overcome this time consuming process, we must use the concept of Un-pickling.
=>The advantange of Un-pickling is that with single read operation, we can read entire record content from
the file of secondary memory into the object of main memory.

Definition of Un-Pickling:
-------------------------------------------
=>The process of reading or trasefering the enrite record content from file of secondary memory into the
object of main memory by performing single read operation is called Un-pickling.

=>Un-Pickling concept participates in Read Operations.


----------------------------------------------------------------
Steps for implementing Un-Pickling Concept:
-----------------------------------------------------------------
=>import pickle module
=>Choose the file name and open it into read mode.
=>Use the load() of pickle module. load() is used for transfering or loading the
entire record content from file of secondary memory into object of main memory.
Syntax: objname=pickle.load(filepointer)
=>NOTE That Un-pickling concept always takes the file in Binary Format.
----------------------------------------------------------------------------------------------------------------
Examples:
----------------------
#Program for reading student details from KBD and save them in file--Program-(A)
#studpick.py
import pickle
def savestuddata():
with open("student.data","ab") as fp:
while(True):
print("-"*50)
sno=int(input("Enter Student Number:"))
sname=input("Enter Student Name:")
marks=float(input("Enter Student Marks:"))
#add student details to list object
lst=list()
lst.append(sno)
lst.append(sname)
lst.append(marks)
print("-"*50)
#save lst data into the file
pickle.dump(lst,fp)
print("Student Object Saves Successfully in file")
print("-"*50)
ch=input("Do u want to insert another record(yes/no):")
if(ch=="no"):
print("Thx for using program")
break

#main program
savestuddata()
---------------------------------------------------------------------
Examples:
----------------------
#Program for reading student records from file
#studunpick.py
import pickle
try:
print("-"*50)
print("Number\tName\tMarks")
print("-"*50)
with open("student.data","rb") as fp:
while(True):
try:
obj=pickle.load(fp)
for val in obj:
print("{}".format(val),end="\t")
print()
except EOFError:
print("-"*50)
break
except FileNotFoundError:
print("File does not exist:")
--------------------------------------------------------------------
Working with CSV Files in Python Programs:
-------------------------------------------------------------
================================================
Working with CSV Files in Python
================================================
=>CSV stannds for Comma Separated Values.
=>A CSV File is one of the is a simple file format used to store tabular data, such as a
spreadsheet or database.
=>A CSV file stores tabular data (numbers and text) in plain text.
=>Each line of the CSV file is a data record. Each record consists of one or more fields,
separated by commas.
=>Python provides an in-built module called csv to work with CSV files.
=>There are 2 classes provided by this module for writing the data to CSV File. They are
1) By using Using csv.writer class object
2) By Using csv.DictWriter class object
---------------------------------------------------
1) By using Using csv.writer class object
----------------------------------------------------
=>The csv.writer class object is used to insert data to the CSV file.
=>To create an object of csv.writer class object, we use writer() and present in csv module.
=>csv.writer class object provides two Functions for writing to CSV file. They are
1) writerow()
2) writerows()

1) writerow(): This Function writes a single row at a time.


Field row / Header can also be written using this Function.
Syntax:- csvwriterobj.writerow(fields Row / Data Row)
2) writerows(): This Function is used to write multiple rows at a time.
This can be used to write rows list.
Syntax: Writing CSV files in Python
csvwriterobj.writerows(data rows)
here data rows can be list, tuple set,frozenset only
--------------------------------------------------------------------------------------------------------------
2) By Using csv.DictWriter class object:
---------------------------------------------------------------
=>The csv.DictWriter class object is used to insert dict data to the CSV file.
=>To create an object of csv.DictWriter class object, we use DictWriter() and present in csv module.
=>csv.DictWriter class object provides two Functions for writing to CSV.
1) writeheader()
2) writerows()
------------------------
1) writeheader():
------------------------
writeheader() method simply writes the first row of your csv file using the pre-specified fieldnames.
Syntax: DictWriterObj.writeheader()
----------------------------------------------------------
2) writerows():
------------------------
=>writerows() method simply writes all the values of (Key,Value) from dict object in the form of separate
rows[ Note: it writes only the values(not keys) ]
Syntax:- DictWriterObj.writerows(dictobject)

----------------------------------------------------------------------------------------------------------------
Reading the data from CSV File
----------------------------------------------------------------------------------------------------------------
=>There are various ways to read a CSV file that uses either the CSV module or the pandas
library.
=>The csv Module provides two classes for reading information from CSV file .
1) csv.reader
2) csv.DictReader
--------------------------
1) csv.reader():
--------------------------
=>This Function is used for creating an object of csv.reader class and It helps us to read the data records
from csv file.
=>Syntax:- csvreaderobj=csv.reader(filepointer)

-------------------------------------------------------------------------------------
2) csv.DictReader():
-----------------------------------
=>This Function is used for creating an object of csv.DictReader class and It helps us to read the data
from csv file where it contains dict data(Key,Value).
=>Syntax:- csvdictreaderobj=csv.DictReader(filepointer)
---------------------------------------------------------------------------------------------------------------------
Examples:
----------------------
#Program for reading the data from CSV File--csv File Approach
#FileCSVDictRead.py------csv module-------reader()
import csv
try:
with open("univ2.csv","r") as fp:
csvdr=csv.DictReader(fp)
for recs in csvdr:
for k,v in recs.items():
print("\t{}-->{}".format(k,v))
print()

except FileNotFoundError:
print("File does not exist:")
------------------------------------------------------------------------------------------------------------------
Examples:
----------------------
#Program for reading the data from CSV File--csv File Approach
#FileCSVModuleEx1.py------csv module-------reader()
import csv
try:
with open("emp.csv","r") as fp:
csvr=csv.reader(fp)
for record in csvr:
for val in record:
print("{}".format(val),end=" ")
print()

except FileNotFoundError:
print("File does not exist:")

--------------------------------------------------------------------------------------------------------------------
Examples:
----------------------
# Python program to demonstrate writing to CSV File
#csvwriteex1.py
import csv
# field names OR Header Names
recfields = ['Name', 'Branch', 'Year', 'CGPA']
# data rows of csv file
rows = [ ['Nikhil', 'COE', '2', '9.0'],
['Sanchit', 'COE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'],
['Sagar', 'SE', '1', '9.5'],
['Prateek', 'MCE', '3', '7.8'],
['Sahil', 'EP', '2', '9.1'] ]
# name of csv file
csvfilename = "univ1.csv"
# writing data to csv file
with open(csvfilename, 'w') as fp:
# creating a csv writer object
csvwriter = csv.writer(fp)
# writing the fields
csvwriter.writerow(recfields)
# writing the data rows
csvwriter.writerows(rows)
print("\nCSV file Created and Verify")
-------------------------------------------------------------------------------------------------------------
Examples:
----------------------
# Python program to demonstrate to write single record
# writing single record to CSV file
#csvwriteex2.py
import csv

# data record of csv file


row = ('Teja', 'IT', '2', '9.9')

# name of csv file


filename = "univ1.csv"
# writing to csv file
with open(filename, 'a') as fp:
# creating a csv writer object
cw = csv.writer(fp)
# writing the data row to the csv file
cw.writerow(row)
print("\nSingle Record Written to the CSV File:")
-----------------------------------------------------------------------------------------------------------------
Examples:
----------------------
#Program for reading the data from CSV File--File Approach
#FileCSV.py
try:
with open("emp.csv","r") as fp:
csvdata=fp.read()
print(csvdata)
except FileNotFoundError:
print("File does not exist:")

Examples:
----------------------
# importing the csv module
#csvdictwriteex2.py
import csv

# my data rows as dictionary objects


mydict =[ {'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'},
{'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'},
{'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'},
{'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'},
{'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'},
{'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'} ]

# field names
csvfields = ['name', 'branch', 'year', 'cgpa']

# name of csv file


filename = "univ2.csv"

# writing to csv file


with open(filename, 'w') as fp:
# creating a csv dict writer object
dictwriter = csv.DictWriter(fp, fieldnames = csvfields)
# writing headers (field names)
dictwriter.writeheader()
# writing data rows
dictwriter.writerows(mydict)
print("\nDict Data Written to the csv file--verify")
--------------------------------------------------------------------------------------------------------------------
OS Module concept Programs:
---------------------------------------------------
============================================
OS Module
============================================
=>os is one of the pre-defined module in python
=>The purpose of 'os' module is that "To perform various OS Based Operations".
=>Some of the OS Based Operations are
a) obtaining current working folder----getcwd()
b) create a folder / Directory--------------mkdir()
c) Create Folder Hierarchy----------------makedirs()
d) delete folder / Directory----------------rmdir()
e) Delete Folder Hierarchy---------------removedirs()
f) Renaming a Folder---------------rename("Old Folder Name","New
Folder Name")
g) Finding Number of Files and Folder in Folder------listdir()
-------------------------------------------------------------------------------------------------------------
a) obtaining current working folder
-------------------------------------------------------------------------------------------------------------
=>To obtain current working folder, we use getcwd() of os module
=>Syntax:- varname=os.getcwd()
-----------------------
Examples:
-----------------------
#Program for obtaining current working folder
#currentworkfolder.py
import os
cw=os.getcwd()
print("Current Working Folder=",cw)
-------------------------------------------------------------------------------------------------------------
b) create a Folder / Directory
-------------------------------------------------------------------------------------------------------------
=>To create a Folder / Directory mkdir()
=>Syntax: os.mkdir("folder name")
=>If the folder name alerady exist then we get FileExistsError
=>mkdir() can create a folder at a time but not possible create Folders Hierarchy (RootFolder\Sub
Folder\Sub-sub folder..etc)

Examples:
----------------------
#Program for creating a folder
#FolderCreate1.py
import os
try:
os.mkdir("D:\KVR")
print("Folder Created--verify")
except FileExistsError:
print("Folder already exist:")
except FileNotFoundError:
print("mkdir() can't create Folders Hierarchy:")
--------------------------------------------------------------------------------------
c) Create Folders Hierarchy:
--------------------------------------------------------------------------------------
=>To create Folders Hierarchy, we use makedirs()
=>Syntax:- os.makedirs("Folder Hierarchy")
=>Here Folder Hierarchy represents RootFolder\Sub Folder\Sub-sub folder..etc.
=>If the Folder Hierarchy alerady exist then we get FileExistsError
----------------
Examples:
-------------------
#Program for creating Folders Hierarchy
#FoldersCreate1.py
import os
try:
os.makedirs("D:\INDIA\HYD\AMPT\PYTHON")
print("Folders Hierarchy created--verify")
except FileExistsError:
print("Folders Hierarchy already exist:")
--------------------------------------------------------------------------------------
d) Delete a Folder / Directory
-------------------------------------------------------------------------------------------------------------
=>To delete a Folder / Directory , we use rmdir()
=>Syntax: os.rmdir("folder name")
=>If the folder name does not exist then we get FileNotFoundError
=>rmdir() can remove one folder at a time but not possible romve Folders Hierarchy (RootFolder\Sub
Folder\Sub-sub folder..etc)
=>rmdir() can remove a folder when folder empty otherwise we get OSError.

Examples:
------------------
#Program for deleting a folder
#FolderRemove1.py
import os
try:
os.rmdir("KVR")
print("Folder Removed--verify")
except FileNotFoundError:
print("Folder does not exist:")
except OSError:
print("Folder is not empty:")

--------------------------------------------------------------------------------------------------------------------
e) Delete a Folders / Directory Hierarchy:
-------------------------------------------------------------------------------------------------------------
=>To delete Folders / Directory hierarchy we use removedirs()
=>Syntax: os.removedirs("folders Hiererchy")
=>If the folders Hiererchy" does not exist then we get FileNotFoundError
=>removedirs() can remove a folder hierarchy when folder empty otherwise we get OSError.

Examples:
------------------
#Program for Removing a folders
#FoldersRemove1.py
import os
try:
os.removedirs("C:\AMEERPET\HYD")
print("Folder Removed--verify")
except FileNotFoundError:
print("Folder does not exist:")
except OSError:
print("Folder is not empty:")
------------------------------------------------------------------------------------------------------------------
f) Renaming a Folder:
------------------------------------------------------------------------------------------------------------------
=>To rename a folder, we use rename() of os module
=>Syntax:- os.rename("Old Folder Name", "New folder name")
=>if Old Folder Name does not exist then we get FileNotFoundError

Examples:
------------------
#Program for re naming a folder
#FolderRename.py
import os
try:
os.rename("C:\HYD","C:\AMEERPET")
print("Folder Renamed--verify")
except FileNotFoundError:
print("Folder name does not exist")
-----------------------------------------------------------------------------------------------------------------
g) Finding Number of Files and Folder in Folder:
-----------------------------------------------------------------------------------------------------------------
=>To list or find number of files in folderm we use listdir()
=>Syntax:- listobj=os.listdir("folder name")
=>If the folder name does not exist then we get FileNotFoundError

Examples:
-----------------------
#Program for listing files of a folders
#FilesInFolder.py
import os
try:
foldername=input("Enter any folder name:")
listobj=os.listdir(foldername)
print("Number of Files :{}".format(len(listobj)))
for file in listobj:
print("\t{}".format(file))
except FileNotFoundError:
print("Folder does not exist:")
---------------------------------------------------------------------
Examples:
----------------------
#Program for obtaining current working folder
#currentworkfolder.py
import os
cw=os.getcwd()
print("Current Working Folder=",cw) # Current Working Folder= E:\KVR-PYTHON-9AM\OS
MODULE
----------------------------------------------------------------------
Examples:
----------------------
#Program for creating a folder
#FolderCreate1.py
import os
try:
os.mkdir("D:\KVR\PYTHON")
print("Folder Created--verify")
except FileExistsError:
print("Folder already exist:")
except FileNotFoundError:
print("mkdir() can't create Folders Hierarchy:")
---------------------------------------------------------------------
Examples:
----------------------
#Program for creating Folders Hierarchy
#FoldersCreate1.py
import os
try:
os.makedirs("D:\INDIA\HYD\AMPT\PYTHON")
print("Folders Hierarchy created--verify")
except FileExistsError:
print("Folders Hierarchy already exist:")
Examples:
----------------------
#Program for Removing a folder
#FoldersRemove.py
import os
try:
os.removedirs("D:\INDIA\HYD\AMPT\\NYTHON")
print("Folder Removed--verify")
except FileNotFoundError:
print("Folder does not exist:")
-----------------------------------------------------------------------
Examples:
----------------------
#Program for Removing a folders
#FoldersRemove1.py
import os
try:
os.removedirs("C:\AMEERPET\HYD")
print("Folder Removed--verify")
except FileNotFoundError:
print("Folder does not exist:")
except OSError:
print("Folder is not empty:")
----------------------------------------------------------------------
Examples:
----------------------
#Program for re naming a folder
#FolderRename.py
import os
try:
os.rename("C:\HYD","C:\AMEERPET")
print("Folder Renamed--verify")
except FileNotFoundError:
print("Folder name does not exist")

---------------------------------------------------------------------------------------------------------------------------
Examples:
----------------------
#Program for listing files of a folders
#FilesInFolder.py
import os
try:
foldername=input("Enter any folder name:")
listobj=os.listdir(foldername)
print("Number of Files :{}".format(len(listobj)))
for file in listobj:
print("\t{}".format(file))
except FileNotFoundError:
print("Folder does not exist:")

You might also like