Python Part3
Python Part3
png
----------------------------------------------------------------------------------------------------------------------------- ---------------------
-----------------------------------------------------------
#bigex1.py
--------------------------
-#This Program accepts two integer values and find big among them.
#bigex1.py
a,b=int(input("Enter Value of a:")), int(input("Enter Value of b:"))
# a=40
b= 40
if(a==b):
print("BOTH VALUES ARE EQUAL:")
else:
if(a>b):
print("{} is bigger than {}".format(a,b))
else:
print("{} is bigger than {}".format(b,a))
--------------------------------------------------------------------------
#bigex2.py
--------------------------
#This Program accepts Three integer values and find big among them.
#bigex2.py
a,b,c=int(input("Enter Value of a:")), int(input("Enter Value of b:")) ,
int(input("Enter Value of c:"))
if(a==b) and (b==c):
print("ALL VALUES ARE EQUAL:")
else:
if(a>b) and (a>c):
print("big({},{},{})={}".format(a,b,c,a))
else:
if(b>a) and (b>c):
print("big({},{},{})={}".format(a,b,c,b))
else:
print("big({},{},{})={}".format(a,b,c,c))
-------------------------------------------------------------------------
#cng.py
----------------------------------
#This program accept a number and obtains a number by changing its sign.
#cng.py
n=int(input("Enter a number:")) # -23
cn= -1*n
print("Given Number={}".format(n))
print("Changed Sign Number={}".format(cn))
-----------------------------------------------------------------------------------
#digitex1.py
---------------------------------------------------------
#Program for accepting any digit and print it name .
#digitex1.py
d=int(input("Enter a digit:"))# d-0 1 2 3 4 5 6 7 8 9
if(d==0):
print("{} is ZERO".format(d))
else: if(d==1):
print("{} is ONE".format(d))
else:
if(d==2):
print("{} is TWO".format(d))
else:
if(d==3):
print("{} is THREE".format(d))
else: if(d==4):
print("{} is FOUR".format(d))
else: if(d==5):
print("{} is FIVE".format(d))
else: if(d==7):
print("{} is SEVEN".format(d))
else: if(d==6):
print("{} isSIX".format(d))
else: if(d==8):
print("{} is EIGHT".format(d))
else: if(d==9):
print("{} isNINE".format(d))
else:
print("{} is NUMBER".format(d))
----------------------------------------------------------------------------------
digitex2.py
---------------------------------
#Program for accepting any digit and print it name
#digitex2.py
d=int(input("Enter a Value:"))# d-0 1 2 3 4 5 6 7 8 9
if d in [1,2,3,4,5,6,7,8,9,0]:
print("{} is a digit".format(d))
else:
print("{} is a number:".format(d))
---------------------------------------------------------------------------------
#digitex3.py
---------------------------------------------
#Program for accepting any digit and print it name.
#digitex3.py
d=int(input("Enter a Value:"))# d-0 1 2 3 4 5 6 7 8 9
if(d==0):
print("{} is ZERO".format(d))
elif(d==1):
print("{} is ONE".format(d))
elif(d==2):
print("{} is TWO".format(d))
elif(d==3):
print("{} is THREE".format(d))
elif(d==4):
print("{} is FOUR".format(d))
elif(d==5):
print("{} is FIVE".format(d))
elif(d==6):
print("{} isSIX".format(d))
elif(d==7):
print("{} is SEVEN".format(d))
elif(d==8):
print("{} is EIGHT".format(d))
elif(d==9):
print("{} is NINE".format(d))
else:
print("{} is NUMBER".format(d))
---------------------------------------------------------------------------------------
#digitex4.py
---------------------------------------
#Program for accepting any digit and print it name #digitex4.py
d=int(input("Enter a Value:"))# d-0 1 2 3 4 5 6 7 8 9
if(d==0):
print("{} is ZERO".format(d))
elif(d==1) or (d==-1):
print("{} is ONE".format(d))
elif(d==2) or (d==-2):
print("{} is TWO".format(d))
elif(d==3) or (d==-3):
print("{} is THREE".format(d))
elif(d==4) or (d==-4):
print("{} is FOUR".format(d)) elif(d==5) or (d==-5):
print("{} is FIVE".format(d)) elif(d==6) or (d==-6):
print("{} is SIX".format(d)) elif(d==7) or (d==-7):
print("{} is SEVEN".format(d)) elif(d==8) or (d==-8):
#NumGenex1.py
-------------------------
#This program accept an integer value (n) and generate 1 to n where n is +ve
#NumGenex1.py
n=int(input("Enter a number:"))
if (n<=0): print("{} invalid input".format(n))
else:
print("Numbers within {}".format(n))
i=1 # Initlization Part while (i<=n): # Cond Part
print("\t{}".format(i)) i=i+1 # Updation Part
---------------------------------------------------------
#NumGenex2.py
-------------------------
#This program accept an integer value (n) and generate 1 to n where n is +ve
#NumGenex2.py
\n=int(input("Enter a number:"))
if (n<=0): print("{} invalid input".format(n))
else:
print("Numbers within {}".format(n)) kvr=1 # Initlization Part while (kvr<=n): # Cond Part print("\t{}".format(kvr))
kvr=kvr+1 # Updation Part
else:
print("\niam from else block")
print("Other statements in Program--while loop")
print("Other statements in Program--if..else loop")
----------------------------------------------------------------------
#NumGenex2.py
-------------------------
#This program accept an integer value (n) and generate n to 1 where n is +ve
#NumGenex2.py
n=int(input("Enter a number:"))
# n=10 output 10 9 8 7 6 ..................................................................................... 1
if(n<=0):
print("{} is invalid input:".format(n))
else:
print("="*50)
print("Number within {}".format(n))
print("="*50) while(n>=1):
# Cond Part
print("\t{}".format(n))
n=n-1 #updation part
else:
print("="*50)
------------------------------------------------------------------
#NatNumsSum.py
-------------------------------------
#This Program find sum of First N Natital Numbers , Squares and Cubes of Natural Numbers.
#NatNumsSum.py
n=int(input("Enter a Number:"))
if(n<=0):
print("{} is invalid Input:".format(n))
else:
print("="*50)
print("\tNat Nums\tSquares\t\tCubes")
print("="*50)
i=1
s,ss,cs=0,0,0
while(i<=n):
print("\t{}\t\t{}\t\t{}".format(i,i**2,i**3))
s=s+i
ss=ss+i**2
cs=cs+i**3
i=i+1
else:
print("="*50) print("\t{}\t\t{}\t\t{}".format(s,ss,cs))
print("="*50)
--------------------------------------------------------
Sumdigits.py
----------------------------------------
#This Program accept the number and find sum of its digits
#Sumdigits.py
n=int(input("Enter anumber:"))
if(n<=0):
print("{} Invalid Input:".format(n))
else:
print("Given Number:{}".format(n))
s=0
while(n>0):
d=n%10
s=s+d
n=n//10
else:
print("Sum of Digits={}".format(s))
========================================
for loop (or) for...else
========================================
Syntax-1
-------------------------------------------------------------------------------------------------------------------------
for varname in Iterable_Object: statement-1 statement-2
------------------------------------------------- ----------------
statement-n
-------------------------------------------------------------------------------------------------------------------------
Other Statements in program
---------------------- ---------------------------------
(OR)
Syntax-2
-------------------------------------------------------------------------------------------------------------------------
for varname in Iterable_Object: statement-1 statement-2
-------------------------------------------------------------------------------------------------------------------------
statement-n
else: else Block of
Statements
=================
Explanation:
=================
=>here 'for' and 'in' are the keywords
=>The execution process of for loop is that " Each element of Iterable-object kept in varname and executes
Indentation Block of statements until all elements in iterable object are completed"
=>here writing 'else' block is optional.
=>After for loop excution, condition becomes false and PVM executes else block of statements(if we write
else) and later executes Other statements in Program
--------------------------------------------------------------------------------------------------
#Forloopex1.py
-------------------------------------------------
s="PYTHON"[::-1]
print("By using while loop")
i=0
while(i<len(s)):
print("\\t{}".format(s[i]))
i=i+1
print("\nby using for loop")
for val in s:
print("\t{}".format(val)
-----------------------------------------------------------------
#forloopex2.py
-----------------------------
#This Program accepts a line of text and obtains each and every character.
#forloopex2.py
line=input("Enter a line of text:") # Python for ch in line
print("{}".format(ch),end=" ")
---------------------------------------------------------
#forloopex3.py
-----------------------
#This Program accepts a line of text and obtains each and every character.
#forloopex3.py
line=input("Enter a line of text:") # Python vow=0
for ch in line:
if ch in ['a','e','i','o','u','A','E','I','O','U']:
vow=vow+1
else:
print("Number of Vowels={}".format(vow))
--------------------------------------------------------
#forloopex4.py
----------------------------------------
#This Program accepts numerical Integer value and display mul table
#forloopex4.py
n=int(input("Enter a number:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
print("-"*50)
print("Mul table for :{}".format(n))
print("-"*50) for i in range(1,21):
print("\t{} x {} ={}".format(n,i,n*i))
else:
print("-"*50)
----------------------------------------------------------
#Factors.py
-----------------------
#Program for printing factor for a Given Number
#Factors.py
n=int(input("Enter a Number:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
print("Given Number:{}".format(n))
print("Factor:")
for i in range(1, n//2+1):
if(n%i==0):
print("\t{}".format(i),end=" ")
------------------------------------------------------------------
#perfect.py
----------------------------------------
#Program for printing factor for a Given Number
#perfect.py
n=int(input("Enter a Number:")) # 8
if(n<=0):
print("{} is invalid input:".format(n))
else:
s=0
print("Given Number:{}".format(n))
print("Factors:")
for i in range(1, n//2+1):
if(n%i==0):
print("\t{}".format(i),end=" ")
s=s+i
else:
if(s==n):
print("\n{} is perfect".format(n))
else:
print("\n{} is not perfect".format(n))
------------------------------------------------------------------------
#Roman.py
---------------------------------
#write a python program which will convert an ordinary number into equivalent
roman number
#Roman.py
n=int(input("Enter a number:")) # 99
if(n<=0):
print("{} is invalid input".format(n))
else:
while(n>=1000):
print("M",end="")
n=n-1000
if(n>=900):
print("CM",end="")
n=n-900
if(n>=500):
print("D",end="")
n=n-500
if(n>=400):
print("CD",end="")
n=n-400
while(n>=100):
print("C",end="")
n=n-100
if(n>=90):
print("XC",end="")
n=n-90
if(n>=50):
print("L",end="")
n=n-50
if(n>=40):
print("XL",end="")
n=n-40
while(n>=10):
print("X",end="")
n=n-10
if(n>=9):
print("IX",end="")
n=n-9
if(n>=5):
print("V",end="")
n=n-5
if(n>=4):
print("IV",end="")
n=n-4
while(n>=1):
print("I",end="")
n=n-1
-----------------------------------------------------------------------
#sortnames.py
-----------------------------
#Program for accepting list of Names and sort them ASCending and Decending order
#sortnames.py
n=int(input("Enter How Many Names u want sort:")) # 6
if(n<=0):
print("{} is invalid".format(n))
else:
lst=list() # create an empty list
for i in range(1,n+1):
val=input("Enter {} Name:".format(i))
lst.append(val) # append the name to lst
else:
print("="*50)
print("Original Names:")
print("="*50)
for name in lst:
print("\t{}".format(name))
else:
print("="*50)
lst.sort()
print("Names in Ascending Order:")
print("="*50)
for name in lst:
print("\t{}".format(name))
else:
print("="*50)
lst.sort(reverse=True)
print("Names in Decending Order:")
print("="*50)
for name in lst:
print("\t{}".format(name))
else:
print("="*50)
---------------------------------------------------------
#sumavg.py
------------------------------------
#Program for accepting list of values and find their sum and average.
#sumavg.py
n=int(input("Enter How Many Number sum u want find:")) # 6
if(n<=0):
print("{} is invalid".format(n))
else:
lst=list() # create an empty list
for i in range(1,n+1):
val=int(input("Enter {} Value:".format(i)))
lst.append(val) # append the value to lst
else:
print("-"*50)
print("Content of list={}".format(lst)) # [12, 23, 10, 25, 2]
print("-"*50)
#find sum and avg
s=0
for val in lst:
s=s+val
else:
print("-"*50)
print("sum={}".format(s))
print("Average={}".format(s/len(lst)))
print("-"*50)
---------------------------------------------------------------------------
#tokens.py
-----------------------------------------
"""Generate
abc1
abc2
abc3
abc4
abc5
-------
abc-n """
#tokens.py
n=int(input("Enter how many tokens u want to generate:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
for i in range(1,n+1):
print("\tabc{}".format(i))
print("============OR============")
for i in range(1,n+1):
print("\tabc",i)
print("============OR============")
for i in range(1,n+1):
print("\tabc"+str(i))
=========================================================================
break statement
========================================================================
=>break is a keyword
=>break statement is used for terminating the execution of loop.
=>In otherwords, when break statement is taken place after satisfying some
condition then PVM stops the Loop exeuction and comes out corresponding loop and
executes other statements in program ( never executes else block of any loop when
break taken place)
-------------------------------------
Syntax:
--------------
for var in Iterable-objec
--------------------------------
if(test cond):
break
---------------------------------
-Other statements
---------------
Syntax:
-------------------------------------
while(Test Cond1)
--------------------------------
if(test cond2):
break
---------------------------------
-Other statements
===========================================================
continue statement
============================================================
=>continue statement is used for making the PVM Control to the top of the loop
by skipping the statements whch are followed by continue keyword when certain
condition is satisfied.
=>when we use continue statement in for and while loop then after the condition
is false of for and while loop then PVM executes else part.
=>continue statement must be used inside of loops.
Syntax1:
--------------
for varname in iterbale_object:
----------------------------
if (test cond):
continue
--------------------------- # statements
written after continue
---------------------------
Syntax2:
--------------
while (Test cond1)
----------------------------
if (test cond2):
continue
--------------------------- # statements
written after continue
---------------------------
---------------------------------------------------------------------------------
---------------------
#breakex1.py
--------------------------------
s="PYTHON"
for ch in s:
print("\t{}".format(ch))
print("--------------------------------")
for ch in s[:4]:
print("\t{}".format(ch))
print("--------------------------------")
for ch in s:
if(ch=="O"):
break
else:
print("\t{}".format(ch))
---------------------------------------------------------------------------------
---
#breakex2.py
--------------------------------
s="PYTHON"
for ch in s:
if(ch=="H"):
break
else:
print("\t{}".format(ch))
---------------------------------------------------------------------------------
#breakex3.py
------------------------------------
lst=[10,20,30,40,50,60,70,80]
for val in lst:
if(val==50):
break
else:
print("\t{}".format(val))
else:
print("i am from for loop--else")
print("Other statements in program")
---------------------------------------------------------------------------------
----
#primeex1.py
-----------------------------------
#Program for accepting an Integer and decide whether it is prime or not
#primeex1.py
n=int(input("Enter a number:")) # 2
if(n<=1):
print("{} is invalid input:".format(n))
else:
result=False
for i in range(2,n):
if (n%i==0):
result=True
break
if(result):
print("{} is NOT PRIME".format(n))
else:
print("{} is PRIME".format(n))
--------------------------------------------------------------------
#primeex2.py
-------------------------------------
#Program for accepting an Integer and decide whether it is prime or not
#primeex2.py
n=int(input("Enter a number:")) # 5
if(n<=1):
print("{} is invalid input:".format(n))
else:
result="PRIME"
for i in range(2,n):
if (n%i==0):
result="NOTPRIME"
break
if(result=="NOTPRIME"):
print("{} is NOT PRIME".format(n))
else:
print("{} is PRIME".format(n))
---------------------------------------------------------------------------------
-
#continueex1.py
--------------------------------------------
s="PYTHON"
for ch in s:
if(ch=="H"):
continue
else:
print("\t{}".format(ch))
------------------------------------------------------------------
#continueex2.py
---------------------------------------
s="PYTHON" # Output : PTHN
for ch in s:
if(ch=="Y") or (ch=="O") :
continue
else:
print("\t{}".format(ch))
else:
print("for loop --else block")
print("Other statements in program")
------------------------------------------------------------
#posnegsum.py
----------------------------------------
#Program for accepting list of values and find sum of +ve and -ve numbers.
#posnegsum.py
n=int(input("Enter How many values u have:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
lst=[] # create an empty list
for i in range(1,n+1):
val=float(input("Enter {} Value:".format(i)))
lst.append(val)
else:
print("="*50)
print("Content of list={}".format(lst))# =[23.0, -45.0, -12.0,
13.0, -45.0, 0.0]
print("="*50)
#find sum of +ve numbers of list
ps=0
for val in lst:
if(val<=0):
continue
else:
ps=ps+val
else:
print("Sum of Possive Numbers={}".format(ps))
#find sum of -ve numbers of list
ns=0
for val in lst:
if(val>=0):
continue
else:
ns=ns+val
else:
print("Sum of Negative Numbers={}".format(ns))
-----------------------------------------------------------------------------
#posnegsumlist.py
--------------------------------------------
#Program for accepting list of values and find sum of +ve and -ve numbers.
#posnegsumlist.py
n=int(input("Enter How many values u have:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
lst=[] # create an empty list
for i in range(1,n+1):
val=float(input("Enter {} Value:".format(i)))
lst.append(val)
else:
print("="*50)
print("Content of list={}".format(lst))# =[23.0, -45.0, -12.0,
13.0, -45.0, 0.0]
print("="*50)
#find sum of +ve numbers of list
ps=0
pslist=list()
for val in lst:
if(val<=0):
continue
else:
pslist.append(val)
ps=ps+val
else:
print("Sum of Possive List
Numbers:{}={}".format(pslist,ps))
#find sum of -ve numbers of list
ns=0
nslist=list()
for val in lst:
if(val>=0):
continue
else:
nslist.append(val)
ns=ns+val
else:
print("Sum of Negative List
Numbers:{}={}".format(nslist,ns))
=========================================================================
Nested or Inner Loops
================================================================
=>The process of defining one loop inside of another loop is called Nested or
Inner Loops.
=>For Every Value of Outer Loop, inner loop executed for finite number of times
until test condition becomes False.
=>We can defined inner loops in 4 Possibilities. They are
45
dsgvnjghsjkdg
-------------------------------------------------------------------------
#innerloopex1.py
-------------------------------
12Val of j-inner for loop:{}".format(j))
else:
print("I am out-of inner for loop")
print("-"*50)
else:
print("I am out-of outer for loop")
"""
Output:
"""
---------------------------------------------------------------------------
#innerloopex2.py
-----------------------------------------
i=1
while(i<=5):
print("Val of i-outer while loop:{}".format(i))
print("-"*50)
j=1
while(j<=3):
print("\tVal of j-inner while loop:{}".format(j))
j=j+1
else:
print("I am out-of inner while loop")
print("-"*50)
i=i+1
else:
print("I am out-of outer while loop")
"""
Output:
E:\KVR-PYTHON-11AM\INNER 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
I am 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
I am 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
I am 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
I am 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
I am out-of inner while loop
--------------------------------------------------
I am out-of outer while loop
"""
---------------------------------------------------------------------------
#innerloopex3.py
----------------------------------------
for i in range(1,6):
print("Val of i-outer for loop:{}".format(i))
print("-"*50)
j=3
while(j>=1):
print("\tVal of j-inner while loop:{}".format(j))
j=j-1
else:
print("I am out-of inner while loop")
print("-"*50)
else:
print("I am out-of outer for loop")
"""
E:\KVR-PYTHON-11AM\INNER LOOPS>py innerloopex3.py
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
I am 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
I am 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
I am 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
I am out-of inner while loop
--------------------------------------------------
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
I am out-of inner while loop
--------------------------------------------------
I am out-of outer for loop
"""
---------------------------------------------------------------------------
#innerloopex4.py
-----------------------------------
i=5
while(i>=1):
print("Val of i-outer while loop:{}".format(i))
print("-"*50)
for j in range(3,0,-1):
print("\tVal of j-inner for loop:{}".format(j))
else:
print("I am out-of inner for loop")
print("-"*50)
i=i-1
else:
print("I am out-of outer while loop")
"""
Output:
=================================================================================
=
=>We know that a String is a collection / sequence of Characters enclosed within
single / double Quotes (or) triple single / double Quotes.
=>String data is of type <class,'str'>
=>To do various opereations on String data, we have to use the following the
functions.
---------------------------------------------------
1) capitalize():
----------------------
=>This function is used for capitalizing the given str data
=>Syntax: varname=strobj.capitalize()
-----------------
Examples:
-----------------
>>> s="python is an oop lang"
>>> print(s,type(s))---------python is an oop lang <class 'str'>
>>> cs=s.capitalize()
>>> print(cs,type(cs))---- Python is an oop lang <class 'str'>
>>> print(s,type(s))---- python is an oop lang <class 'str'>
---------------------------------------------------------------------------
2) title():
----------------------------
=>This Function is used for getting all words First Characters as capital.
=>Syntax:- varname=strobj.title()
Examples:
----------------
>>> s="python is an oop lang"
>>> ts=s.title()
>>> print(ts,type(ts))--------Python Is An Oop Lang <class 'str'>
>>> print(s,type(s))-----python is an oop lang <class 'str'>
----------------------------------------------------------------------------
3) find():
---------------------
=>This function is used for finding an index of the first occurance of specified
str data in the given str data.
=>If the data found then it returns Its +ve index value
=>If the data not found then it returns -1
Syntax:- varname=strobj.isalnum()
(or)
strobj.isalnum()
-------------------
Examples:
-----------------
>>> s="12345"
>>> b=s.isalnum()
>>> print(b)------------True
>>> s="python12345"
>>> s.isalnum()----------True
>>> s="python12345#"
>>> s.isalnum()---------False
>>> s="python 12345"
>>> s.isalnum()----------False
>>> s="Python is an oop lang"
>>> s.isalnum()-----------False
>>> s="python"
>>> s.isalnum()--------True
----------------------------------------------------------------------------
5) isalpha():
-----------------------------
=>This Function returns True provided str data contains only Alphabets
otherwise it returns False.
=>Syntax:- varname=strobj.isalpha()
Examples:
-----------------
>>> s="Python"
>>> b=s.isalpha()
>>> print(b)------------True
>>> s="1234"
>>> print(s.isalpha())--------False
>>> s="python1234"
>>> print(s.isalpha())-------False
>>> s="python_1234"
>>> print(s.isalpha())-------False
----------------------------------------------------------------------------
6) isdigit():
-------------------
=>This Function returns True provided str data contains only purly digits(0-9)
otherwise it returns False.
Syntax:- varname=strobj.isdigit()
or
strobj.isdigit()
Examples:
-----------------
>>> a="1234"
>>> print(a.isdigit())------------True
>>> a="pyth1234"
>>> print(a.isdigit())--------False
>>> a="python"
>>> print(a.isdigit())------False
>>> a="pyth#$123"
>>> print(a.isdigit())---------False
----------------------------------------------------------------------------
7) islower() :
--------------------
=>This Function returns True provided the str data is completely available in
lowercase otherwise it returns False.
Syntax:- varname=strobj.islower()
or
strobj.islower()
Examples:
-----------------
>>> s="python"
>>> print(s.islower())----------True
>>> s="Python"
>>> print(s.islower())---------False
>>> s="python is an oop lang"
>>> print(s.islower())----True
>>> s="python is An oop lang"
>>> print(s.islower())-------False
---------------------------------------------------------------------------
8) isupper() :
--------------------
=>This Function returns True provided the str data is completely available in
upper case otherwise it returns False.
Syntax:- varname=strobj.isupper()
or
strobj.isupper()
Examples:
------------------
>>> s="Python"
>>> print(s.isupper())----------False
>>> s="PYTHON"
>>> print(s.isupper())-------True
>>> s="python is an oop lang"
>>> print(s.isupper())---------False
>>> s="PYTHON IS AN OOP LANG"
>>> print(s.isupper())-------True
----------------------------------------------------------------------------
9) isspace()
-------------------
=>This Function returns True provided str data contains purely space otherwise it
returns False.
=>Syntax:- varname=strobj.issapce()
(or)
strobj.isapce()
Examples:
-----------------
>>> s="Python is an oop"
>>> print(s.isspace())--------False
>>> s=" "
>>> print(s.isspace())--------True
>>> s=" "
>>> print(s.isspace())--------True
>>> s="123 345"
>>> print(s.isspace())---False
>>> s="" # empty string
>>> s.isspace()-----------False
----------------------------------------------------------------------------
10) upper():
--------------------
=>This Function is used for converting lower case data into upper case data.
Syntax:- varname=strobj.upper()
11) lower():
--------------------
=>This Function is used for converting upper case data into lower case data.
Syntax:- varname=strobj.lower()
Examples:
-----------------
>>> s="python is an oop lang"
>>> uc=s.upper()
>>> print(uc)-------PYTHON IS AN OOP LANG
>>> print(s)-------python is an oop lang
>>> print(uc)---- PYTHON IS AN OOP LANG
>>> lc=uc.lower()
>>> print(lc)-------- python is an oop lang
----------------------------------------------------------------------------
12) join():
--------------
=>This Function is used concatinating all the sequence of values which are
available in the form str
Syntax:- varname=strobj1.join(iterable obj)
Examples-:
----------------
>>>tpl=('java', 'python', 'Data Science')
>>> print(tpl, type(tpl))--('java', 'python', 'Data Science') <class 'tuple'>
>>> s2=""
>>> s3=s2.join(tpl)
>>> print(s3)---->javapythonData Science
--------------------------
>>> lst=["Apple","Mango","Kiwi","Guava"]
>>> frs=""
>>> frs=frs.join(lst)
>>> print(frs)-------------------AppleMangoKiwiGuava
>>> lst=["Apple","Mango","Kiwi","Guava"]
>>> frs=" "
>>> frs=frs.join(lst)
>>> print(frs)--------------Apple Mango Kiwi Guava
----------------------------------------------------------------------------13)
split():
--------------------
=>This function is used for splitting the given str data into different tokens
based spitting value. The default splitting value is space
=>This Function returns splitting values in the form of list.
Syntax:- listobj=strobj.split()
listobj=strobj.split("spliting value")
Examples:
----------------
>>> s="Python is an oop lang"
>>> s.split()--------- ['Python', 'is', 'an', 'oop', 'lang']
>>> s="9-11-2021"
>>> l=s.split("-")
>>> print(l)----------['9', '11', '2021']
>>> s="apple#kiwi#guava-banana"
>>> l=s.split("#")
>>> print(l)----------['apple', 'kiwi', 'guava-banana']
>>> l[2].split("-")--------['guava', 'banana']
============================X====================================
#alphabets.py
--------------------------
line=input("Enter line of text:") # ab4#5b$k@58afH%
vs=[]
cs=[]
ds=[]
ss=[]
for ch in line:
if ch in ["A","E","I","O","U", "a","e","i","o","u"] :
vs.append(ch)
elif( ch not in ["A","E","I","O","U", "a","e","i","o","u"] and
ch.isalpha() ):
cs.append(ch)
elif(ch.isdigit() ):
ds.append(ch)
else:
ss.append(ch)
else:
print("="*50)
print("Given Line:{}".format(line))
print("Vowels List={}".format(vs))
print("Cons List={}".format(cs))
print("Digits List={}".format(ds))
print("Special Symbols list={}".format(ss))
print("="*50)
----------------------------------------------------------------------------
#indexex.py
---------------------------
line=input("Enter line of text:") # Python
i=0
for ch in line:
print("Character :{}--->Index:{} and orginal Index={}".format( ch,
line.index(ch),i ))
i=i+1
----------------------------------------------------------------
#indexex1.py
------------------
line=input("Enter line of text:") # Python
for ch in line:
print("Character :{}--->Index:{} ".format( ch, line.find(ch) ))
--------------------------------------------------------------------------
============================================================================
Introduction to Functions in Python
==========================================================
=>The purpose of Functions is that "To Perform Certain Operation and Provides
Code
Re-usability ".
=>In this context, we have two types of Programming Languages. They are
a) Un-Structured Programming Languages
b) Structured Programming Languages
#main program
result=mulop(10,20) # Function Call
print("Mul result=",result)
result=mulop(-4,-6) # Function Call
print("Mul result=",result)
result=mulop(-5,8) # Function Call
print("Mul result=",result)
-------------------------------------------------------------------------------
#mulex2.py
---------------------
def mulop(a,b): # Function Definition, here a and b are called Formal Params
c=a*b
return c
#main program
x=float(input("Enter First Value:"))
y=float(input("Enter Second Value:"))
res=mulop(x,y)
print("mul({},{})={}".format(x,y,res))
----------------------------------------------------
#mulex3.py
---------------
def mulop():
#Taking Inputs
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
#Process
c=a*b
#disply the result
print("mul({},{})={}".format(a,b,c))
#main program
mulop()
--------------------------------------------------------
#mulex4.py
------------------------
def mulop(k,v):
r=k*v
print("mul({},{})={}".format(k,v,r))
#main program
x=float(input("Enter First Value:"))
y=float(input("Enter Second Value:"))
mulop(x,y)
----------------------------------------------------------
#mulex5.py
----------------------------
def mulop():
#taking Input
x=float(input("Enter First Value:"))
y=float(input("Enter Second Value:"))
#process
z=x*y
#return the result
return z
#main program
res=mulop()
print("Mul result=",res)
----------------------------------------------------------
#Approachno1.py
--------------------------------
#Taking Input : From Function Call
#Doing Procees: Inside Function Body
#Disply Result: Function Call
def arearect(l,b):
a=l*b
return a
#main program
l=float(input("Enter Length:"))
b=float(input("Enter Breadth:"))
res=arearect(l,b)
print("Area of Rectangle:{}".format(res))
---------------------------------------------------------
#Approachno2.py
----------------------
#Taking Input : Inside of Function Body
#Doing Procees: Inside Function Body
#Disply Result: Inside Function Body
def arearect():
#taking input
l=float(input("Enter Length:"))
b=float(input("Enter Breadth:"))
#process
a=l*b
#display the result
print("Area of Rectangle={}".format(a))
#main program
arearect()
--------------------------------------------------------------
#Approachno3.py
-------------------------------
#Taking Input : from Function Call
#Doing Procees: Inside Function Body
#Disply Result: Inside Function Body
def arearect(l,b):
a=l*b
print("Area of rectangle={}".format(a))
#main program
l=float(input("Enter Length:"))
b=float(input("Enter Breadth:"))
arearect(l,b)
------------------------------------------------------------------
#Approachno4.py
-----------------------------
#Taking Input : Inside of Function Body
#Doing Procees: Inside Function Body
#Disply Result: Function Call
def arearect():
#taking input
l=float(input("Enter Length:"))
b=float(input("Enter Breadth:"))
#process
a=l*b
#return the result
return a
#main program
result=arearect()
print("Area of Rectangle={}".format(result))
---------------------------------------------------------------
#Approachno5.py
----------------------------------
#Taking Input : Inside of Function Body
#Doing Procees: Inside Function Body
#Disply Result: Function Call
def arearect():
#taking input
l=float(input("Enter Length:"))
b=float(input("Enter Breadth:"))
#process
a=l*b
#return the result
return l,b,a
#main program
l1,b1,result=arearect()
print("Area of Rectangle({},{})={}".format(l1,b1,result))
print("===============OR====================")
k=arearect() # Here k variable is holding all three values and whose type is
tuple.
print("Area of Rectangle({},{})={}".format(k[-3],k[-2],k[-1]))
============================================================================
ADDITIONAL PROGRAMS IN FUNCTIONS
==========================================================
#write a python program which demonstrates the concept of accepting iterable
objects as parameters
#FunwithIterableobj.py
-----------------------------------------------------------------------
def disp(kv):
print("-"*50)
print("Type of kv of disp()=",type(kv))
print("-"*50)
for x in kv:
print("\t{}".format(x))
print("-"*50)
def show(kanth):
print("-"*50)
print("Type of kanth in show()=",type(kanth))
print("-"*50)
for x,y in kanth.items():
print("\t{}--->{}".format(x,y))
print("-"*50)
#main program
lst=[10,20,30,40,50,60,"Python"]
disp(lst)# Function call
tpl=(10,"Rossum",34.56,True,2+3j)
disp(tpl)# Function call
s="PYTHON"
disp(s) # Function Call
fs=frozenset({10,20,30,"Python","Django"})
disp(fs) # Function Call
d={10:"Python",20:"Django",30:"Data Sci",40:"ML"}
show(d)
----------------------------------------------------------------------------
#Write a python program which will accept list of numerical values and find their
sum and average by using functions
#listsumavg.py
------------------------------------------------------------
def readlistvalues():
n=int(input("Enter How many values u want to enter:"))
if(n<=0):
print("Invalid input")
exit()
else:
lst=[] # create empty list
for i in range(1,n+1):
val=float(input("Enter {} Value:".format(i)))
lst.append(val)
return lst
def findlistsumsvg(lst):
print("-----------------------------------")
print("Content of list:")
print("-----------------------------------")
for val in lst:
print("\t{}".format(val))
print("-----------------------------------")
#find sum and avg
s=0
for val in lst:
s=s+val
else:
print("Sum={}".format(s))
print("Avg={}".format(s/len(lst)))
print("-----------------------------------")
#main program
kvlist=readlistvalues()
findlistsumsvg(kvlist)
--------------------------------------------------------------------
#write a python program which will write a python program which will accept a
line of text and find the occurrence each letter
# HINT INPUT : PYTHON PRO
""" P--------------------2
Y--------------------1
T--------------------1
H--------------------1
O--------------------2
N--------------------1
" " ------------1
P---------------------2
R---------------------1
O--------------------2 """
#findoccurences.py
import time
def findoccurences():
line=input("Enter a Line of Text:") # PYTHON PRO
lst=list(line) # lst= ['P', 'Y', 'T', 'H', 'O', 'N', ' ', 'P', 'R', 'O']
print("-"*50)
print("Given Line={}".format(line))
print("-"*50)
for ch in line[::-1]:
print("Character: {} and Number of Occurences:
{}".format(ch,lst.count(ch)))
time.sleep(1)
else:
print("-"*50)
#main program
findoccurences()
---------------------------------------------------------------------------
#write a python program which will accept list of words. accept a word and search
in the list of words. if it is found display search is successful otherwise
search is unsuccessful.
#searchexample.py
--------------------------------------------------------------------
def readtext():
text=input("Enter a text:") # test="Python is an oop lang"
lst=text.lower().split()
return lst # ['Python', 'is', 'an', 'oop', 'lang']
def searchword(lst1,wrd1):
if wrd1.lower() in lst:
return True
else:
return False
#main program
lst=readtext()
wrd=input("Enter a word to search in list of words:")
result=searchword(lst,wrd)
if (result ):
print("Search is Successful:")
else:
print("Search is Un Successful:")
---------------------------------------------------------------------------
=================================================
Arguments and Parameters
=================================================
=>In Python Programming, we have two types of Parameters. They are
a) Formal Parameters (or ) Variables
b) Local Paramaters (or) Variables
=>The Formal Parameters are used in Function Heading and They are used for
storing Inputs coming from Function Calls.
=>The Local Paramaters are used in Function Body and thye are used storing
Temporary results of Function Logic
=>Arguments are also Variables used in Function Calls. In other words Arguments
are called Actual Arguments ( Global Varaibles )
----------------------------------------------------------------------------
==================================================
1) Possitional Arguments (or) Parameters
==================================================
=>The Concept of Possitional Parameters (or) arguments says that "The Number of
Arguments(Actual arguments ) must be equal to the number of formal parameters ".
=>This Parameter mechanism also recommends Order and Meaning of Parameters for
Higher accuracy.
=>Python Programming Environment follows by default Possitional Arguments (or)
Parameters.
-----------------------------------------------
Syntax for Function Definition :
-----------------------------------------------
def functionname(parm1,param2.....param-n):
-------------------------------------------------
Syntax for Function Call:
-----------------------------------------------
functionname(arg1,arg2....arg-n)
=>Here the values of arg1,arg2...arg-n are passing to param-1,param-2..param-n
respectively.
==================================x=======================================
=============================================
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)
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).
----------------------------------------------------------------------------
#Program for arguments and parameters
#PossArgex1.py
--------------------------------------------
def compute(x,y,z): # Here 'x' 'y' and 'z' are called Formal Parameters
k=x+y+z
print("result=",k)
#main program
a=10
b=20
c=30
compute(a,b,c) # Function Call---'a' 'b' and 'c' are called arguments.
compute(100,200,300) # Function Call 100,200,300 arguments values
---------------------------------------------------------------------------
#PosArgex2.py
---------------------------------------
def showinfo(sno,sname,marks):
print("\t{}\t{}\t{}".format(sno,sname,marks))
#main program
print("="*50)
print("\tStno\tName\tMarks")
print("="*50)
showinfo(10,"RS",22.22) # Fun Call
showinfo(20,"TR",44.44) # Fun Call
showinfo(30,"DR",55.55) # Fun Call
print("="*50)
----------------------------------------------------------------------------
#PosArgex3.py
-----------------------------
def showinfo(sno,sname,marks,crs):
print("\t{}\t{}\t{}\t{}".format(sno,sname,marks,crs))
#main program
print("="*50)
print("\tStno\tName\tMarks\tCourse")
print("="*50)
showinfo(10,"RS",22.22,"PYTHON") # Fun Call
showinfo(20,"TR",44.44,"PYTHON") # Fun Call
showinfo(30,"DR",55.55,"PYTHON") # Fun Call
showinfo(40,"ST",65.55,"PYTHON") # Fun Call
showinfo(50,"RR",15.55,"PYTHON") # Fun Call
print("="*50)
---------------------------------------------------------------------------
#DefaultArgex1.py
-------------------------------
def showinfo(sno,sname,marks,crs="PYTHON"):
print("\t{}\t{}\t{}\t{}".format(sno,sname,marks,crs))
#main program
print("="*50)
print("\tStno\tName\tMarks\tCourse")
print("="*50)
showinfo(10,"RS",22.22) # Fun Call
showinfo(20,"TR",44.44) # Fun Call
showinfo(30,"DR",55.55) # Fun Call
showinfo(40,"ST",65.55) # Fun Call
showinfo(50,"RR",15.55) # Fun Call
showinfo(60,"KR",45.55,"JAVA") # Fun Call
showinfo(70,"UR",15.55,"JAVA") # Fun Call
showinfo(60,"KR",45.55,"JAVA_PYTHON") # Fun Call
print("="*50)
----------------------------------------------------------------------
#DefaultArgex2.py
------------------------------
def disp(a=1,b=2,c=3):
print("\t{}\t{}\t{}".format(a,b,c))
#main program
print("="*50)
print("\tA\tB\tC")
print("="*50)
disp()
disp(10)
disp(10,20)
disp(10,20,30)
#disp(10,20,30,40)-----Error
print("="*50)
--------------------------------------------------------------------
#DefaultArgex3.py
-----------------------------------------
def JavaCourse(sno,sname,smarks,crs="JAVA"):
print("\t{}\t{}\t{}\t{}".format(sno,sname,smarks,crs))
def PythonCourse(sno,sname,smarks,crs="PYTHON"):
print("\t{}\t{}\t{}\t{}".format(sno,sname,smarks,crs))
def CCourse(sno,sname,smarks,crs="C"):
print("\t{}\t{}\t{}\t{}".format(sno,sname,smarks,crs))
#main program
print("="*50)
print("\tStno\tName\tMarks\tCourse")
print("="*50)
JavaCourse(10,"RS",22.22) # Fun Call
JavaCourse(20,"TR",44.44) # Fun Call
PythonCourse(30,"DR",55.55) # Fun Call
PythonCourse(40,"ST",65.55) # Fun Call
CCourse(50,"RR",15.55) # Fun Call
CCourse(60,"KR",45.55) # Fun Call
PythonCourse(70,"UR",15.55) # Fun Call
CCourse(60,"KR",45.55) # Fun Call
print("="*50)
----------------------------------------------------------------------------
KEYWORD PArameters (or)arguments Variables Length Parameters(or)arguments Programs
----------------------------------------------------------------------------------------------------------------------------- ---------------
#kwdargseex1.py
------------------------------------------------------
def dispempinfo(eno,ename,sal,cname):
print("\t{}\t{}\t{}\t{}".format(eno,ename,sal,cname))
#main program
print("\tEmpno\tName\tSal\tCname")
print("="*50)
dispempinfo(111,"Rossum",34.56,"PSF")# Fun call with Possitional args
dispempinfo(222,"Vijay",cname="TCS",sal=64.55)# Fun call with Possitional args
and Keyword args
dispempinfo(sal=3.4,eno=333,cname="Wipro",ename="Raj")# Fun call with Keyword
args
#disp(cname="HCL",eno=555,"Mani",6.7) ---SyntaxError: positional argument follows
keyword argument
dispempinfo(444,"Sanjay",5.6,cname="HCL")
print("="*50)
----------------------------------------------------------------------------------------------------------------------------- -------
#kwdargseex2.py
----------------------------------------------------
def dispempinfo(eno,ename,sal,cname,cnt="INDIA"):
print("\t{}\t{}\t{}\t{}\t{}".format(eno,ename,sal,cname,cnt))
#main program
print("\tEmpno\tName\tSal\tCname\tCountry")
print("="*50)
dispempinfo(111,"Rossum",34.56,"PSF")# Fun call with Possitional args
dispempinfo(222,"Vijay",cname="TCS",sal=64.55)# Fun call with Possitional args
and Keyword args
dispempinfo(sal=3.4,eno=333,cname="Wipro",ename="Raj")# Fun call with Keyword
args
#disp(cname="HCL",eno=555,"Mani",6.7) ---SyntaxError: positional argument follows
keyword argument
dispempinfo(444,"Sanjay",5.6,cname="HCL")# Fun call with Possitional args and
Keyword args
dispempinfo(555,"Trump",55.66,"Poli","USA") # Fun call with Possitional args
dispempinfo(666,cnt="RSA",cname="HIT",ename="Sagar",sal=55.55)
dispempinfo(cname="CA",ename="Ram",sal=5.8,eno=777)
print("="*50)
----------------------------------------------------------------------------------------------------------------------------- -------
"""Output
a b c d
----------------------------------
10 20 30 40 """
#kwdargseex3.py
----------------------------------------
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)
disp(d=40,c=30,a=10,b=20)
disp(b=20,d=40,a=10,c=30)
disp(10,d=40,c=30,b=20)
#disp(d=40,c=30,b=20,10) SyntaxError: positional argument follows keyword
argument
disp(10,20,d=40,c=30)
print("="*50)
-------------------------------------------------------------------
"""Output
a b c d
----------------------------------
10 20 30 40 """
#kwdargseex4.py
----------------------------------------------------------
def disp(a=10,b=20,c=30,d=40):
print("\t{}\t{}\t{}\t{}".format(a,b,c,d))
#main program
print("="*50)
print("\ta\tb\tc\td")
print("="*50)
disp()
disp(10,20,30,40)
disp(d=40,c=30,a=10,b=20)
disp(b=20,d=40,a=10,c=30)
disp(10,d=40,c=30,b=20)
#disp(d=40,c=30,b=20,10) SyntaxError: positional argument follows keyword
argument
disp(10,20,d=40,c=30)
print("="*50)
-------------------------------------------------------------------
#varlenargsex1.py
-----------------------------------
-This Program will not execute as it is written bcoz PVM remebers latest Function
definition
def disp(a): # Function Def-1
print("{}".format(a))
#main program
disp(10) # Function call--1
disp(10,20) # Function call--2
disp(10,20,30)# # Function call--3
disp(10,20,30,40)# # Function call--3
-------------------------------------------------------------------
#varlenargsex2.py
--------------------------
This Program will execute
def disp(a): # Function Def-1
print("{}".format(a))
#main program
disp(10) # Function call--1
disp(10,20) # Function call--2
disp(10,20,30)# # Function call--3
disp(10,20,30,40)# # Function call--4
disp(10,20,30,40,"Python")# # Function call--5
disp("C","CPP","JAVA","PYTHON","DS","ML") # Function call--6
disp() # Function call--7
---------------------------------------------------------
=>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)
----------------------------------------------------------
#Program demonstarting Keyword Variable Length Arguments (or) Parameters
#kwdvarlenargex1.py
--------------------------------
#main program
showinfo(sno=10,sname="Ram",M1=40,M2=50,M3=60) # Function Call-1
showinfo(eno=20,ename="Raj",sal=6.7,dsg="SE") # Function Call-2
showinfo(tno=40,tname="Rakesh",subject="Python") # Function Call-3
----------------------------------------------------------
#Program demonstarting Keyword Variable Length Arguments (or) Parameters
#kwdvarlenargex2.py
-------------------------------
This Program will execute
def showinfo(sno,sname,M1,M2,M3): # Function Def-1
print("\t{}\t{}\t{}\t{}\t{}".format(sno,sname,M1,M2,M3))
showinfo(sno=10,sname="Ram",M1=40,M2=50,M3=60) # Function Call-1
print("-"*50)
def showinfo(eno,ename,sal,dsg): # Function def-2
print("\t{}\t{}\t{}\t{}".format(eno,ename,sal,dsg))
def showinfo(**n):
print("-"*50)
print("Type of n={} and Number of elements ={}".format(type(n),len(n)))
print("-"*50)
for x,y in n.items():
print("\t{}--->{}".format(x,y))
else:
print("-"*50)
#main program
showinfo(sno=10,sname="Ram",M1=40,M2=50,M3=60) # Function Call-1
showinfo(eno=20,ename="Raj",sal=6.7,dsg="SE") # Function Call-2
showinfo(tno=40,tname="Rakesh",subject="Python") # Function Call-3
showinfo(cno=50,cname="Naresh")
showinfo(name="Agarwal")
showinfo()
----------------------------------------------------------
#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")
----------------------------------------------------------
#write a python program which will calculate total marks of different subjects
secured by different students who are studding in different classes
#purekwdvarlenargex4.py
----------------------------------------
def findtotalmarks(sname,cls,**submarks):
print("-"*50)
print("Student Name:{}".format(sname))
print("Student Class :{}".format(cls))
print("-"*50)
totmarks=0
print("\tSub Name \t Marks")
print("-"*50)
for s,m in submarks.items():
print("\t{}\t\t{}".format(s,m))
totmarks=totmarks+m
print("-"*50)
print("\tTotal Marks={}".format(totmarks))
print("-"*50)
#main program
findtotalmarks("Narayan","X",Eng=66,Hindi=55,Maths=88,Sci=77,Soc=66,Tel=55)
findtotalmarks("Antaryami","XII",Phy=55,Che=50,Maths=75)
findtotalmarks("Srikanth","B.Tech",C=60,CPP=70,PYTHON=55,OS=66)
findtotalmarks("Jawed","Research")
----------------------------------------------------------
===========================================
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 use for Representing Common values for
Multiple Different 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
===================================================================
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.
=======================================================================
#globallocalvarex1.py
---------------------------------
lang="PYTHON" # Global Variable
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()
---------------------------------------------------------------------------
#globallocalvarex2.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()
-------------------------------------------------------------------
#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()
---------------------------------------------------------------------------------
------
#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.
-------------------------------------------------------------------
======================================
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====================================
#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
------------------------------------------------------------------
#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():
-----------------------------------------------------------------
=================================================
Anonymous Functions (or) Lambda Functions
=================================================
=>Anonymous Functions advanced features of Normal Functions.
=>Anonymous Functions are those which does not contain Name explicitly.
=>The Purpose of Anonymous Functions is that " To Perform Instant Operations ".
=>Instant Operations are those which can used at that point of time only and no
longer
interested to re-use in other programs.
=>To develop any Anonymous Functions , we use a keyword called "lambda" and
Anonymous Functions also called Lambda Functions.
=>Anonymous Functions contains Single Executable Statement but not containing
multiple
Lines of Statements.
=>Anonymous Functions returns the result of single executable statement
automatically and
there is no need to return the value with return statement.
---------------------------------------------------------------
Syntax:-
varname=lambda params-list : Expression
Explanation:
------------------
=>"varname" is an object of <class,'function'> and hence Indirectly varname acts
as
Function name.
=>lambda is a keyword used developing Anonymous Functions .
=>Params-list represents list of formal parameter(s) and they are used for
Storing the results
coming from function call.
=>Expression represents a Single executable statement and provides solution for
Instant
Operation.
----------------------------------------------------------------
#Program for adding of two number by using Normal Function and Anonymous
Functions
#NormalAnonymousex1.py
def addop(a,b): # Normal Function Definition
c=a+b
return c
#main program
print("type of addop is=",type(addop)) # <class 'function'>
result1=addop(101,201) # Normal Function Call
print("Sum=",result1)
print("-------------------------------------------")
print("type of sumop is=",type(sumop)) # <class 'function'>
result2=sumop(1001,2001)
print("Sum=",result2)
-------------------------------------------------------------
#Program for adding of two number by using Normal Function and Anonymous
Functions
#NormalAnonymousex2.py
def addop(a,b): # Normal Function Definition
c=a+b
return c
#main program
x,y=float(input("Enter First Value:")), float(input("Enter First Value:"))
result1=addop(x,y) # Normal Function Call
print("Sum=",result1)
print("-------------------------------------------")
result2=sumop(x,y)
print("Sum=",result2)
-------------------------------------------------------------------
#write a python program which will accept two numerical values and find the
biggest among them by using Anonymous functions
#Anonymousex3.py
#Anonymous function Definiton
big=lambda a,b : a if a>b else b
#main program
x,y=float(input("Enter First Value:")), float(input("Enter First Value:"))
bigval=big(x,y) # Anonymous function call
print("Big({},{})={}".format(x,y,bigval))
----------------------------------------------------------------------------
#write a python program which will accept two numerical values and find the
biggest among them by using Anonymous functions
#Anonymousex3.py
#Anonymous function Definiton
big=lambda a,b : a if a>b else b
#main program
x,y=float(input("Enter First Value:")), float(input("Enter First Value:"))
bigval=big(x,y) # Anonymous function call
print("Big({},{})={}".format(x,y,bigval))
------------------------------------------------------------------
#write a python program which will accept three numerical values and find
baggiest and smallest by considering equality of values by using using Anonymous
functions
#Anonymousex5.py
big=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
small=lambda k,v,r : "All Value are equal" if (k==v) and (v==r) else k if (k<v)
and (k<r) else v if (v<k) and (v<r) else r
#maijn program
x,y,z=float(input("Enter First Value:")), float(input("Enter Second Value:")),
float(input("Enter Third Value:"))
print("Big({},{},{})={}".format(x,y,z, big(x,y,z)) )
print("Small({},{},{})={}".format(x,y,z, small(x,y,z)) )
------------------------------------------------------------------
#write a python program which will accept list of values and find the max and min
form list of values by using Anonymous Functions
#Anonymousex6.py
big=lambda lst: max(lst)
#maijn program
lst=[] # empty list
while(True):
val=input("Enter Value (press 'stop' enter):")
if(val.lower()=="stop"):
break
else:
lst.append(int(val))
if(len(lst)==0):
print("List does not contain any elements and we can't find big and
small")
elif(len(lst)==1):
print("Both the Values of List are same and it itself is max and min")
else:
print("max({})={}".format(lst,big(lst)))
print("min({})={}".format(lst,small(lst)))
-----------------------------------------------------------------
=========================================
Special Functions in Python
=========================================
=>In Python Programming, we have 3 special Functions. They are
1) filter ()
2) map()
3) reduce()
---------------------------------------------------------------------------------
---------
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 the that element will be neglected ".
This process will be continued until all elements of Iterable object completed.
-----------------------------------------------------------
#filterex1.py
-------------------
Normal Functions
def positive(n): # Normal Function-1
if(n>0):
return True
else:
return False
#main program
lst=[10,20,-45,-0,-67,3,-12,8,45,-56,34,2]
obj1=filter(positive, lst)
obj2=filter(negative, lst)
print("type of obj1=",type(obj1)) # type of obj= <class 'filter'>
print("content of obj1=",obj1) # <filter object at 0x0000023A83D70400>
#convert filter object into list type
pslist=list(obj1)
pslist.sort()
nslist=list(obj2)
nslist.sort()
print("="*50)
print("Given Elements=",lst)
print("Possitive List of Elements=",pslist)
print("Negative List of Elements=",nslist)
-------------------------------------------------------------
#filterex2.py-
Anonymous Functions
positive=lambda n: n>0 # Anonymous Function-1
negative=lambda x : x<0 # Anonymous Function-2
#main program
lst=[10,20,-45,-0,-67,3,-12,8,45,-56,34,2]
pslist=list(filter(positive,lst))
nslist=list(filter(negative,lst))
pslist.sort()
nslist.sort()
print("="*50)
print("Given Elements=",lst)
print("Possitive List of Elements=",pslist)
print("Negative List of Elements=",nslist)
print("="*50)
----------------------------------------------------------------------
#filterex3.py---Anonymous Functions
lst=[2,12,3,13,4,14,5,15,-1,-11,0,2]
pslist=list(filter(lambda n: n>0 , lst)) # Filter with Anonymous Function-1
nslist=list(filter(lambda x : x<0 , lst)) # Filter with Anonymous Function-2
pslist.sort()
nslist.sort()
print("="*50)
print("Given Elements=",lst)
print("Possitive List of Elements=",pslist)
print("Negative List of Elements=",nslist)
print("="*50)
---------------------------------------------------------------------
#write a python program which will accept list of numerical integers. filter even
numbers and odd numbers form list of numbrs
#filterex4.py
lst=[]
while(True):
val=input("Enter Value (press 'q' to stop ):")
if(val=="q"):
break
else:
lst.append(int(val))
if(len(lst)==0):
print("List empty, can't do any thing")
else:
#define a filter for filtering Even Number
evenlist=list(filter(lambda n: n%2==0, lst))
#define a filter for filtering Odd Number
oddlist=list(filter(lambda n: n%2!=0, lst))
print("="*50)
print("Given Elements=",lst)
print("Even List of Elements=",evenlist)
print("Odd List of Elements=",oddlist)
print("="*50)
-----------------------------------------------------------------
write a python program which will accept list of numerical integers. filter even
numbers and odd numbers form list of numbrs
#filterex5.py
print("Enter list of elements separated by space:")
lst=[int(val) for val in input().split() ] # " 12 34 21 32 55 56 34 66 4 2 "
#define a filter for filtering Even Number
evenlist=list(filter(lambda n: n%2==0, lst))
#define a filter for filtering Odd Number
oddlist=list(filter(lambda n: n%2!=0, lst))
print("="*50)
print("Given Elements=",lst)
print("Even List of Elements=",evenlist)
print("Odd List of Elements=",oddlist)
print("="*50)
---------------------------------------------------------------------
#write a python program which will accept list of numerical integers. filter even
numbers and odd numbers form list of numbrs
#filterex6.py
print("Enter list of elements separated by comma:")
lst=[int(val) for val in input().split(",") ] # 12,34,56,67,12,3,4,23
#define a filter for filtering Even Number
evenlist=list(filter(lambda n: n%2==0, lst))
#define a filter for filtering Odd Number
oddlist=list(filter(lambda n: n%2!=0, lst))
print("="*50)
print("Given Elements=",lst)
print("Even List of Elements=",evenlist)
print("Odd List of Elements=",oddlist)
print("="*50)
--------------------------------------------------------------------
====================================
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.
---------------------------------------------------------------------------------
------
#mapex1.py
def hike(sal):
sal=sal+sal*0.1
return sal
#main program
oldsal=[10,12,5,6,13,23,24,6,2]
obj=map(hike,oldsal)
print("type of obj=",type(obj)) # type of obj= <class 'map'>
print("content of obj=",obj) # content of obj= <map object at 0x0000019252610400>
newsal=tuple(obj)
print("Old Salaries=",oldsal)
print("New Salaries=",newsal)
--------------------------------------------------------
#mapex2.py
def hike(sal):
sal=sal+sal*0.1
return sal
#main program
print("Enter Old Salaries of Employees separated by space:")
oldsal=[int(sal) for sal in input().split()]
print("Enter Companay Names separated by space:")
clist=[str(cname) for cname in input().split()]
newsal=list(map(hike,oldsal))
print("-"*50)
print("\tOld Salaries\tNew Salaries\tCompany Name")
print("-"*50)
for ols,nls,cls in zip(oldsal,newsal,clist):
print("\t{}\t\t{}\t\t{}".format(ols,nls,cls))
print("-"*50)
----------------------------------------------------------------
#mapex3.py
hike=lambda sal : sal+sal*0.1 # Anonymous Function
#main program
print("Enter Old Salaries of Employees separated by space:")
oldsal=[int(sal) for sal in input().split()]
print("Enter Companay Names separated by space:")
clist=[str(cname) for cname in input().split()]
newsal=list(map(hike,oldsal))
print("-"*50)
print("\tOld Salaries\tNew Salaries\tCompany Name")
print("-"*50)
for ols,nls,cls in zip(oldsal,newsal,clist):
print("\t{}\t\t{}\t\t{}".format(ols,nls,cls))
print("-"*50)
--------------------------------------------------
#mapex4.py
print("Enter Old Salaries of Employees separated by space:")
oldsal=[int(sal) for sal in input().split()]
incr=float(input("Enter the percentange of Increment:"))
print("Enter Companay Names separated by space:")
clist=[str(cname) for cname in input().split()]
newsal=list(map(lambda sal:sal+sal*incr/100,oldsal))
print("-"*50)
print("\tOld Salaries\tNew Salaries\tCompany Name")
print("-"*50)
for ols,nls,cls in zip(oldsal,newsal,clist):
print("\t{}\t\t{}\t\t{}".format(ols,nls,cls))
print("-"*50)
--------------------------------------------------------
#write a python program which will accept list of numerical values and obtains
its squares and square roots
#mapex5.py
print("Enter List of Values separated by space:")
nlist=[int(val) for val in input().split()]
sqrlist=list(map(lambda val:val**2, nlist))
sqrtlist=list(map(lambda val:val**0.5, nlist))
print("="*50)
print("Original Value\tSquare Value\tSquare Root Value:")
print("="*50)
for ol,srv,sqrtv in zip(nlist,sqrlist,sqrtlist):
print("\t{}\t\t{}\t\t{}".format(ol,srv,round(sqrtv,2)))
print("="*50)
----------------------------------------------------------------
#write a python program which will add two lists elements by using map funcation
#mapex6.py
lst1=[10,20,30,40,50,60]
lst2=[100,200,300,400,500,600,700,800]
lst3=list(map(lambda x,y: x+y, lst1,lst2))
print("="*50)
print("\tList1\tList2\tSum List:")
print("="*50)
for x,y,z in zip(lst1,lst2,lst3):
print("\t{}\t{}\t{}".format(x,y,z))
print("="*50)
--------------------------------------------------
#write a python program which will add two lists elements by using map funcation
#mapex7.py
print("Enter List of values for First List:")
lst1=[int(val) for val in input().split()]
print("Enter List of values for Second List:")
lst2=[float(val) for val in input().split()]
lst3=list(map(lambda x,y: x+y, lst1,lst2))
print("="*50)
print("\tList1\tList2\tSum List:")
print("="*50)
for x,y,z in zip(lst1,lst2,lst3):
print("\t{}\t{}\t{}".format(x,y,z))
print("="*50)
---------------------------------------------------------
#write a python program which will accept list of Employees salaries (say
,0,1000,2000,3000) give 10% hike for those employees whose salary ranges between
0 to 5000 give 20% hike for those employees whose salary ranges between 5000 and
more.
#mapfilterex.py
print("Enter List of Salaries of Employee Separated Space:")
salist=[int(sal) for sal in input().split()]
less5000=list(filter(lambda sal: sal>=0 and sal<=5000, salist))
newsal5000=list(map(lambda sal:sal+sal*0.1, less5000))
print("="*50)
print("Salary Less Than 5000\tNew Salary after hike:")
print("="*50)
for ol,nl in zip(less5000,newsal5000):
print("\t{}\t\t{}".format(ol,nl))
print("="*50)
more5000=list(filter(lambda sal: sal>=5001 , salist))
newmore5000=list(map(lambda sal:sal+sal*0.2, more5000))
print("="*50)
print("Salary more Than 5000\tNew Salary after hike:")
print("="*50)
for ol,nl in zip(more5000,newmore5000):
print("\t{}\t\t{}".format(ol,nl))
print("="*50)
--------------------------------------------------------------
#assignment.py
line=input("Enter a line of text:")
print("Given Line={}".format(line)) # PYTHON
#filter for vowels
vlist=list(filter(lambda ch: ch in ['a','e','i','o','u','A','E','I','O','U'],
line ))
clist=list(filter(lambda ch: ch not in ['a','e','i','o','u','A','E','I','O','U']
and ch.isalpha(), line ))
dlist=tuple(filter(lambda k: k.isdigit(),line))
splist=tuple(filter(lambda k: k not in ['a','e','i','o','u','A','E','I','O','U']
and not (k.isalpha()) and not(k.isdigit()), line))
print("-"*50)
print("Vowels List={}".format(vlist))
print("Consonants List={}".format(clist))
print("Digits list List={}".format(dlist))
print("Special Symbols list List={}".format(splist))
print("-"*50)
-----------------------------------------------------------------
================================
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:- 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() belongs to functools
import functools
lst=[345,12,-123,45,67,12,43,234,-56,78]
bv=functools.reduce(lambda k,v: k if k>v else v, lst)
print("biggest={}".format(bv))
sv=functools.reduce(lambda k,v: k if k<v else v, lst)
print("smallest={}".format(sv))
-------------------------------------------------------------
from functools import reduce
print("Enter List of values separated by space:")
lst=[int(val) for val in input().split()]
bv=reduce(lambda k,v: k if k>v else v, lst)
print("biggest={}".format(bv))
sv=reduce(lambda k,v: k if k<v else v, lst)
print("smallest={}".format(sv))
----------------------------------------------------------
lst=[4,3,7,-2,6,3]
newlst=[ val*2 for val in lst ]
print("old list=",lst)
print("new list=",newlst) # [ 8, 6, 14,-4,12,6 ]
--------------------------------------------------
#program finding sum of values of list by using reduce()
import functools
print("Enter list of values separated #:")
lst=[float(val) for val in input().split("#")]
print(type(lst))
print("="*50)
print("Given List={}".format(lst))
s=functools.reduce(lambda a,b:a+b,lst )
print("sum={}".format(s))
print("="*50)
-----------------------------------------------------------
#write a python program which will accept list of words and concatenate them as a
single line of text
#redex4.py
import functools
print("Enter list of words separated by comma:")
x=( str(val) for val in input().split(",") ) # It is not a tuple comprehensions.
print(x)
t=tuple(x) # convert an object of "generator" into an object of tuple
print("type of t=",type(t))
print("-"*50)
print("Content of tuple={}".format(t)) # ('HYD', 'is', 'cap', 'of', 'TS')
line=functools.reduce(lambda a,b: a+" "+b , t)
print("Concatenated Result={}".format(line))
---------------------------------------------------------------
==========================================
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 cating 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 ]
------------------------------------------------------------------