Programs To Teach
Programs To Teach
Program-1
print("Hello World")
output:
"Hello World"
Description of (Program-1)
In the above program I am calling print function and passing only argument of type string i.e “Hello
World”. So print function prints the given argument on the console monitor/terminal/standard output
device and also moves the cursor to the new line
Program-2:
Description of (Program-2)
In the above program I am calling print function and passing two arguments. The first argument is string
i.e. “Hello World” and second keyword argument is also a string i.e “*”. So print function prints the given
two argument on the console monitor/terminal/standard output device in the same line and doesn’t
moves the cursor to the new line.
If you want to stay on the same line after printing the given data (arguments) what should you have to
do?
Cursor will be moved to the new line after printing given arguments to the print function.
Program-3:
a = 10
print("a=", a)
output:
a= 10
Description of (Program-3)
Program-4:
a = 10
b = 20
c = a+b
print(a, "+", b, "=", c)
output:
10 + 20 = 30
Description of (Program-4)
In the above example we have passed 5 arguments to the print function
1. first argument is int i.e a
2. second argument is string i.e “+”
3. third argument is int i.e b
4. fourth argument is string i.e. “=”
5. fifth argument is int i.e c
so print function prints the both arguments and moves the cursor to the new line
Program-5
print()
output:
Description of (Program-5)
In the above program we are calling print function but not passing any arguments. So print function
moves the cursor to the new line
Program-6
s1 = input()
print("s1:\t", s1)
output:
madhu tech skills
s1: madhu tech skills
If you want to take the data from keyboard we have to call input function in python
Description of program-6
In the above program we are calling input() function and haven’t passed any argument so it waits in the
console monitor to take the input/data from keyboard. it won’t print anything because we haven’t
passed anything
Program-7:
s1 = input("Enter anything:\t")
print("s1:\t", s1)
output:
Enter anything: madhu tech skills
s1: madhu tech skills
Description of program-7
In the above program we are calling input() function and passing one argument called “Enter anything:\
t” so input() function prints the given argument, and after that it waits in the console monitor to take
the input/data from keyboard.
Ans. string
1. Input function prints the given argument and waits there in the console monitor to take the
input
2. if you press enter after giving input from the keyboard, it takes the input/data from the
keyboard
3. And It returns the taken data as string to us
4. Now we have to store the returned string in a variable with the support of assignment operator
output:
Enter int value: 10
Type of s1: <class 'str'>
s1: 10
Type of a: <class 'int'>
a: 10
Description of program-8
1. In the above program as a input we are entering a value called 10, this 10 will be taken by input
function and returns it as a string, Now we are storing return value(string) in variable s1.
2. in the second statement we are converting string into integer by passing variable s1(string) to
the int class constructor and storing the converted int value in a variable called ‘a’
Note: if you want to perform arithmetic operations we have to convert string into a numeric type
Program-9
output:
Enter int value: 10
Type of a: <class 'int'>
a: 10
Description of program-9
1. In the above program as a input we are entering a value called 10, this 10 will be taken by input
function and returns it as a string, I am passing the returned value to int constructor directly in
the same statement and storing the converted int value in a variable called ‘a’
Program-10(example on arithmetic operators)
output:
Enter int value: 2
Enter int value: 10
b is bigger
Program-13
output-1:
Enter your country: bharath
Enter your age: 18
You are eligible to vote
a = int(input("a:\t"))
b = int(input("b:\t"))
c = int(input("c:\t"))
if (a == b == c):
print("all are equal")
elif a > b:
if a > c:
print("a is greater")
else:
print("c is greater")
elif b > c:
print("b is greater")
else:
print("c is greater")
output:
a: 100
b: 100
c: 100
all are equal
a = 100
print("a={a}") # output: a={a}
print(f"a={a}") # output: a=100
output:
a={a}
a=100
output:
Enter float value: 10.60
Enter another float value: 2.00
10.6/2.0=5.3
10.6//2.0=5.0
name = "madhu"
rs = "Your Name is %s" % name
print(rs)
print("My Name is %s" % name)
output:
Your Name is madhu
My Name is madhu
a = 10
b = 20
print("a=%s and b=%s" % (a, b))
# after % brackets must for multiple values to pring
output:
a=10 and b=20
output:
Enter float value: 10
Enter another float value: 2
10.000000+2.000000=12.000000
10.000000-2.000000=12.000000
Note: %s works fine to print any value or object. The letter code after the % refers to how the output
should be formatted, not necessarily what data type the input is; in particular, %s just means "whatever
the str(...) function returns
Note: No need to know about in-depth about old formatting style because no-body is using it now
everybody using new style of formatting.
a = 10
b = 20
print("a={0} and b={1}".format(a, b))
# to the format function i have passed two paramaters a,b
# a value will be replaced with place holder {0}
# b value will be replaced with place holder {1}
output:
a=10 and b=20
a = 10
b = 20
print("a={x} and b={y}".format(x=a, y=b))
# to the format function i have passed two paramaters a,b
# a value will be replaced with place holder {x}
# b value will be replaced with place holder {y}
output:
a=10 and b=20
Logical Operators
print("r1:\t", r1)
print("r2:\t", r2)
print("r3:\t", r3)
print("r4:\t", r4)
output:
r1: True
r2: False
r3: False
r4: False
a = int(input("a:\t"))
b = int(input("b:\t"))
c = int(input("c:\t"))
if a > b and a > c:
print(f"{a} is greater")
elif b > c:
print(f"{b} is greater")
elif c > a:
print(f"{c} is greater")
else:
print("All are same")
Output-1:
a: 100
b: 100
c: 100
All are same
output:
r1: True
r1: True
r3: True
r4: False
print("1. add")
print("2. sub")
print("3. multi")
opt = int(input("Enter your option in integer:\t"))
if (opt == 1 or opt == 2 or opt == 3):
a = int(input("Enter int value:\t"))
b = int(input("Enter another int value:\t"))
if opt == 1:
c = a+b
print(f"{a}+{b}={c}")
elif opt == 2:
c = a-b
print(f"{a}-{b}={c}")
elif opt == 3:
c = a*b
print(f"{a}*{b}={c}")
else:
print("Invalid Option")
output-1:
Enter any string: a
a is Vowel
Note: collection objects are also called as collection literals and all the collection or sequence objects are
also called as iterable objects.
1. string
2. range
3. list
4. tuple
5. set
6. frozenset
7. dict
etc….
Program-36(example on range)
output:
elements existed in range object
0
1
2
3
4
5
6
7
8
9
10
n = int(input("Enter n value:\t"))
# r1 = range(1, n+1)
r1 = range(1, n+1, 1)
print("Elements existed in range object")
for ele in r1:
print(ele)
output:
Enter n value: 10
Elements existed in range object
1
2
3
4
5
6
7
8
9
10
n = int(input("n:\t"))
print(f"{n} to 1 elements")
for i in range(n, 0, -1):
print(i)
output:
n: 10
10 to 1 elements
10
9
8
7
6
5
4
3
2
1
n = int(input("n:\t"))
print(f"Even numbers from 0 to {n}")
for i in range(0, n+1, 2):
print(i)
output:
n: 10
Even numbers from 0 to 10
0
2
4
6
8
10
n = int(input("n:\t"))
print(f"Odd numbers from 0 to {n}")
for i in range(1, n+1, 2):
print(i)
output:
n: 11
Odd numbers from 0 to 11
1
3
5
7
9
11
n = int(input("n:\t"))
print(f"Odd numbers from {n} to 1")
if n % 2 == 0:
n = n-1
for i in range(n, 0, -2):
print(i)
output:
n: 10
Odd numbers from 10 to 1
9
7
5
3
1
n = int(input("n:\t"))
print(f"Even numbers from {n} to 0")
if n % 2 != 0:
n = n-1
for i in range(n, -1, -2):
print(i)
output:
n: 11
Even numbers from 11 to 0
10
8
6
4
2
0
n = int(input("n:\t"))
print(f"Factors of {n} Are:")
for i in range(1, n+1):
if (n % i == 0):
print(i)
n = int(input("n:\t"))
print(f"Factors of {n} Are:")
count = 0
for i in range(1, n+1):
if (n % i == 0):
print(i)
count += 1
output:
n: 10
Factors of 10 Are:
1
2
5
10
Factors count of 10 Is 4
Program-45(Program to compare 3 numbers in depth)
a=int(input("a:"))
b=int(input("b:"))
c=int(input("c:"))
if a==b==c:
print("a,b,c are equal")
elif a>b:
if a>c:
print("a is largest")
elif c>a:
print("c is largest")
else:
print("a,c are largest")
elif a==b:
if a>c:
print("a,b are largest")
else:
print("c is largest")
elif b>c:
print("b is largest")
elif c>b:
print("c is largest")
else:
print("b,c are largest")
output:
program-46
s1=input("a:\t")
s2=input("b:\t")
s3=input("c:\t")
if s1.isnumeric() and s2.isnumeric() and s3.isnumeric():
print("Nuvvu manchoniviraaa...")
a=int(s1)
b=int(s2)
c=int(s3)
if(a==b==c):
print("All are same")
elif a>b and a>c:
print("A is greater")
elif b>c:
print("B is greater")
else:
print("C is greater")
else:
print("Nee lathkoor mokhamla naa cheppu.... Wrong input istaaavraaaa")
n=5
count=0
#r=1,2,3,4,5
#count=0,1,2
for i in range(1,n+1):
if n%i==0:
count+=1
print(i)
else:
if(count==2):
print(f"{n} is prime")
else:
print(f"{n} is Not A prime")
output:
1
5
5 is prime
n=int(input("n:\t"))
flag=True
if n in [0,1]:
flag=False
else:
for i in range(2,n):
if(n%i==0):
flag=False
break;
if flag:
print(f"{n} is Prime")
else:
print(f"{n} is Not a Prime")
n=int(input("n:"))
f=1
for i in range(1,n+1):
f*=i
print(f"factorial of {n} is {f}")
output:
n:5
factorial of 5 is 120
# n=input("n:\t")
# for ch in n:
# print(ch)
n=int(input("n:\t"))
while n>0:
r=n%10
print(r)
n=n//10
output:
n: 153
3
5
1
s1=input("n:") #153
digit_count=len(s1)
n=int(s1) #n=153
temp=n; #temp=153
arm=0
while n>0:
r=n%10 #r=3,5,1
arm=arm+r**digit_count; #arm=0,27,152,153
n=n//10 #n=153,15,1,0
if temp==arm:
print(f"{temp} is armstrong")
else:
print(f"{temp} is Not armstrong")
output:
n:1634
1634 is armstrong
*
**
***
****
*****
n=int(input("n:\t"))
for i in range(1,n+1):
print("*"*i)
Program-55(program to print below pattern)
*****
****
***
**
*
Program
n=int(input("n:\t"))
for i in range(n,0,-1):
print("*"*i)
*
**
***
****
*****
Program
n=int(input("n:\t"))
#n=5
#i=1
for i in range(1,n+1,1):
print( (" "*(n-i))+("* "*i) )
1
12
123
1234
12345
Program
n=int(input("n:\t"))
for i in range(1,n+1,1):
for j in range(1,i+1):
print(j,end=" ")
print()
Program-58(progrra to print below pattern using single for loop)
1
12
123
1234
12345
n=int(input("n:\t"))
r1=range(1,n+1)
for i in r1:
print(*r1[0:i])
alphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
n=int(input("entere a number between(2,27):\t"))
for i in range(1,n+1):
print(alphabets[0:i])
n=int(input("n:\t"))
for i in range(65,n+65):
for j in range(65,i+1):
print(chr(j),end=" ")
print()
output:
n: 5
A
A B
A B C
A B C D
A B C D E
Program-61(creating a tuple with zero and single element)
t1=()
t2=tuple()
print("t1:\t",t1)
print("t2:\t",t2)
t1=(10)
print("Type of t1:\t",type(t1))
t1=(10,)
print("Type of t1:\t",type(t1))
output:
t1: ()
t2: ()
t1=(10,20,30,40,50)
t2=tuple(range(1,11))
print("t1:\t",t1,type(t1))
print("t2:\t",t2,type(t2))
t3=tuple(t1)
print("t3:\t",t3,type(t3))
t4=tuple("madhu tech skills")
print("t4:\t",t4,type(t4))
output:
t1: (10, 20, 30, 40, 50) <class 'tuple'>
t2: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) <class 'tuple'>
t3: (10, 20, 30, 40, 50) <class 'tuple'>
t4: ('m', 'a', 'd', 'h', 'u', ' ', 't', 'e', 'c', 'h', ' ', 's', 'k', 'i',
'l', 'l', 's') <class 'tuple'>
t1=(10,20,30,40,50)
print("t1[::-1]",t1[::-1])
print("t1[0]",t1[0])
print("t1[-1]",t1[-1])
#t1[0]=100 no no no no
t1=(10,20,30,10,30,20,10,40,40,50)
i1=t1.index(50)
print("index of 50:\t",i1)
i2=t1.index(10)
print("index of 10:\t",i2)
i3=t1.index(10,1)
print("index of 10:\t",i3)
i4=t1.index(10,4,len(t1))
print("index of 10:\t",i4)
c=t1.count(10)
print(f"10 is existed {c} times")
output:
t1[::-1] (50, 40, 30, 20, 10)
t1[0] 10
t1[-1] 50
index of 50: 9
index of 10: 0
index of 10: 3
index of 10: 6
10 is existed 3 times
t1=(10,20,15,7,18,2)
s1=sorted(t1)
s2=sorted(t1,reverse=True)
print("Type of s1\t",type(s1))
print("s1:\t",s1)
print("s2:\t",s2)
t2=(1,5,False,10,True,3)
s3=sorted(t2)
print("s3:\t",s3)
output:
s1={10,20,30,40,50,60,70,80,19,100}
print("Type of s1:\t",type(s1))
print("s1:\t",s1)
s1.add(200)
print("s1:\t",s1)
#print("s1[0]:\t",s1[0]) #Error set doesn't support indexing
d_ele1=s1.pop()
print("deleted element is:\t",d_ele1)
s2=s1.copy()
print("s1:\t",s1)
print("s2:\t",s2)
s1.remove(50)
print("s1 after deleting 50:\t",s1)
#s1.remove(150)
#print("s1 after deleting 50:\t",s1)
s1.clear()
print("s1 after clear:\t",s1)
output:
Type of s1: <class 'set'>
s1: {100, 70, 40, 10, 80, 50, 19, 20, 60, 30}
s1: {100, 70, 40, 200, 10, 80, 50, 19, 20, 60, 30}
deleted element is: 100
s1: {70, 40, 200, 10, 80, 50, 19, 20, 60, 30}
s2: {70, 40, 200, 10, 80, 50, 19, 20, 60, 30}
s1 after deleting 50: {70, 40, 200, 10, 80, 19, 20, 60, 30}
s1 after clear: set()
s1={10,20,30,40,50}
s2={10,30,40,60,70}
s3=s1.intersection(s2)
print("s1:\t",s1)
print("s2:\t",s2)
print("s3:\t",s3)
s1.intersection_update(s2) #union_update
print("s1:\t",s1)
output:
s1={10,20,30,40,50}
s2={10,30,40,60,70}
s3=s1.difference(s2)
print("s1:\t",s1)
print("s2:\t",s2)
print("s3:\t",s3)
s1.difference_update(s2)
print("s1:\t",s1)
output:
s1={10,20,30,40,50}
s2={10,30,40,60,70}
s3=s1.symmetric_difference(s2)
print("s1:\t",s1)
print("s2:\t",s2)
print("s3:\t",s3)
s1.symmetric_difference_update(s2)
print("s1:\t",s1)
output:
s1={10,20,30,40,50}
s2={10,30,40,60,70}
flag=s1.isdisjoint(s2)
print("s1:\t",s1)
print("s2:\t",s2)
print("s1.isdisjoint(s2):\t",flag)
s1=set(range(1,11))
s2=set((1,2,3,4,5))
flag=s1.issuperset(s2)
print("s1:\t",s1)
print("s2:\t",s2)
print("s1.issuperset(s2):\t",flag)\
flag=s1.issubset(s2)
print("s1:\t",s1)
print("s2:\t",s2)
print("s1.issubset(s2):\t",flag)
d1={1:"madhu",2:"shekar",3:"GiriBabu"}
print("Type of d1:\t",type(d1))
print("d1:\t",d1)
name1=d1.get(2)
name2=d1[3]
print("name1:\t",name1)
print("name2:\t",name2)
d1.update({4:"SobhaRani",5:"Priya"})
print("d1:\t",d1)
d1.popitem()
print("d1:\t",d1)
d1.pop(4)
print("d1:\t",d1)
d1.update({1:"madhu babu"})
print("d1:\t",d1)
output:
name1: shekar
name2: GiriBabu
d1: {1: 'madhu', 2: 'shekar', 3: 'GiriBabu', 4: 'SobhaRani', 5: 'Priya'}
d1: {1: 'madhu', 2: 'shekar', 3: 'GiriBabu', 4: 'SobhaRani'}
d1: {1: 'madhu', 2: 'shekar', 3: 'GiriBabu'}
d1: {1: 'madhu babu', 2: 'shekar', 3: 'GiriBabu'}
d1={1:"madhu",2:"shekar",3:"GiriBabu",4:"Sobha"}
keys=d1.keys() #it retursn dict_keys class object
vals=d1.values()
print("keys:\t",keys)
print("vals:\t",vals)
print("keys..................")
for key in keys:
print(key)
print("values..................")
for value in vals:
print(value)
output:
keys..................
values..................
madhu
shekar
GiriBabu
Sobha
Students1=dict.fromkeys(range(1,101))
Students2=dict.fromkeys(range(1,101), "hello")
print(students1)
print(students1)
marks={
1:{"c":90,"cpp":95,"python":100},
2:{"c":96,"cpp":90,"python":99},
3:{"c":76,"cpp":89,"python":94},
};
#search and returns it's corresponding value if key is found
# if key is not found then adds as new element and returns value
s1marks=marks.setdefault(1,{"c":100,"cpp":100,"python":100})
print("s1marks=",s1marks)
s4marks=marks.setdefault(4,{"c":100,"cpp":100,"python":100})
print("s4marks=",s4marks)
print("marks=",marks)
output:
s1marks= {'c': 90, 'cpp': 95, 'python': 100}
s4marks= {'c': 100, 'cpp': 100, 'python': 100}
marks= {1: {'c': 90, 'cpp': 95, 'python': 100}, 2: {'c': 96, 'cpp': 90, 'python':
99}, 3: {'c': 76, 'cpp': 89, 'python': 94},
4: {'c': 100, 'cpp': 100, 'python': 100}}
d1={1:"Madhu",2:"Priya"}
di=d1.items() #dict_items class object is iterable object
for t1 in di:
print(t1)
output:
(1, 'Madhu')
(2, 'Priya')
d1={1:"Madhu",2:"Priya"}
di=d1.items() #dict_items class object is iterable object
print("di=",di)
for key,value in di:
print(key,value)
output:
di= dict_items([(1, 'Madhu'), (2, 'Priya')])
1 Madhu
2 Priya
Program-78(Hacker rank problem)
n=int(input())
#n=4
if n%2!=0:
print("weird")
elif (n>=2 and n<=5) or n>20:
print("not weird")
elif (n>=6 and n<=20):
print("weird")
Frozen set
1. it is an immutable set
f1=frozenset(range(1,6))
print("f1=",f1)
f2=frozenset(range(1,21,3))
print("f2=",f2)
f3=f1.union(f2)
print("f1.union(f2)=",f3)
f4=f1.intersection(f2)
print("f1.intersection(f2)=",f4)
f5=f1.difference(f2)
print("f1.difference(f2)=",f5)
f6=f1.symmetric_difference(f2)
print("f1.symmetric_difference(f2)=",f6)
output:
f1= frozenset({1, 2, 3, 4, 5})
f2= frozenset({1, 4, 7, 10, 13, 16, 19})
f1.union(f2)= frozenset({1, 2, 3, 4, 5, 7, 10, 13, 16, 19})
f1.intersection(f2)= frozenset({1, 4})
f1.difference(f2)= frozenset({2, 3, 5})
f1.symmetric_difference(f2)= frozenset({2, 3, 5, 7, 10, 13, 16, 19})
Functions
1. function is a block which contains re-usable set of statements
2. we write a function to perform a task
3. we can write a function by u sing a keyword called ‘def’
Advantage:
1. code re-usability
Program-80(Basic example on creating a function)
def add():
a=100
b=200
c=a+b
print(c)
def add():
a=int(input("a:\t"))
b=int(input("b:\t"))
c=a+b
print(f"{a}+{b}={c}")
add()
output:
a: 10
b: 20
10+20=30
def fun1(n):
if n%2==0:
print(f"{n} is even")
else:
print(f"{n} is odd")
fun1(10)
fun1(1)
fun1(5)
fun1(6)
output:
10 is even
1 is odd
5 is odd
6 is even
def fun1(a,b):
c=a+b
return c
r1=fun1(10,2)
r2=fun1(10,20)
r3=fun1(100,200)
print("r1:\t",r1)
print("r2:\t",r2)
print("r3:\t",r3)
output:
r1: 12
r2: 30
r3: 300
add(10,2)
sub()
sub(100)
sub(100,2)
output:
10+2=12
0-0=0
100-0=100
100-2=98
Program-85(program on keyword arguments)
def result(sno,sname,c,java,python):
print(f"Sno:\t{sno}")
print(f"Sname:\t{sname}")
print(f"C:\t{c}")
print(f"Java:\t{java}")
print(f"Python:\t{python}")
result(c=100,sno=1,java=120,sname="Dhanush",python=150)
output:
def fun1(*marks):
print(marks)
def fun2(**marks):
print(marks)
fun1(99,89,98,100,89)
fun1(99,89,98)
fun1()
fun2(c=100,cpp=99,java=100)
fun2(c=100,cpp=99,java=100,python=120,oracle=99)
def fun1():
print("outer function")
def fun2():
print("Inner function")
fun2()
fun1()
output:
outer function
Inner function
Porgram-88( Function returning another function)
def fun1():
print("outer function")
def fun2():
print("Inner function")
return fun2
f=fun1()
f()
output:
outer function
Inner function
def kd1(n):
return n*2
kd2=lambda n:n*2
r1=kd1(1)
print("kd1(1):\t",r1)
r2=kd2(2)
print("kd2(2):\t",r2)
output:
kd1(1): 2
kd2(2): 4
def fun1(f2):
x=f2(10,2)
print("x=",x)
print("2**3=",f2(2,3))
fun1(lambda a,b:a**b)
output:
x= 100
2**3= 8
Program-91(Packing example)
def student(sno,sname,*marks):
print(f"sno:\t{sno}")
print(f"sname:\t{sname}")
print(f"Marks:\t{marks}")
print(f"Total Marks:\t{sum(marks)}")
student(101,"Buddhimanthudu",99,88,89,98,78)
def result(c,cpp,java,oracle,python):
print(f"C:\t{c}")
print(f"Cpp:\t{cpp}")
print(f"Java:\t{java}")
print(f"Oracle:\t{oracle}")
print(f"Python:\t{python}")
l1=[99,100,89,78,89]
result(*l1)#result(99,100,89,78,89)
Program-93(Packing in to a dictionary)
def student_result(sno,sname,**marks):
print("Student details")
print("Sno:\t",sno)
print("Sname:\t",sname)
print("Marks:\t",marks)
student_result(1,"shriya",c=100,cpp=100,java=100,python=110,oracle=100)
student_result(1,"Shriya",**{"c":100,"cpp":99,"java":89,"python":210,"oracle":89
})
student_result(2,"Priya",*[100,99,89,210,89])
output:
Student details
Sno: 1
Sname: Shriya
c: 100
cpp: 99
java: 89
python: 210
oracle: 89
Student details
Sno: 2
Sname: Priya
c: 100
cpp: 99
java: 89
python: 210
oracle: 89
Map()
1. map class is used to map the iterable object elements with a function. After mapping it collects
the values returned by function
2. map objects are 1 time iterable objects
m=map(lambda n:n**2,range(1,11))
print("m=",m)
# l1=list(m)
# print("l1=",l1)
print("using for loop...........")
for ele in m:
print(ele,end=" ")
output:
m= <map object at 0x000002993D8EAA70>
1 4 9 16 25 36 49 64 81 100
s1="10 20 30 40 50"
l1=s1.split()
print("s1=",s1)
print("l1=",l1)
s1="amma.chduvukodaniki book ichav, amma. vanostey godugichav. ammma. andukey
nuvvu naaku nachav"
l2=s1.split(".")
print("l2=",l2)
output:
s1= 10 20 30 40 50
l1= ['10', '20', '30', '40', '50']
l2= ['amma', 'chduvukodaniki book ichav, amma', ' vanostey godugichav', '
ammma', ' andukey nuvvu naaku nachav']
Program-97()
Input: 2 3 5 7 6
Output:[4,9,25,49,36]
s1=input()
#s1="2 6 9 4 6"
l1=s1.split()
m1=map(int,l1)
m2=map(lambda x: x**2,m1)
l2=list(m2)
print(l2)
output:
2 3 5 7 6
[4, 9, 25, 49, 36]
Input: 2 3 5 7 6
Output:[4,9,25,49,36]
print(list(map(lambda x:x**2,map(int,input().split()))))
output:
2 3 5 7 6
[4, 9, 25, 49, 36]
filter()
1. Filter class is used to map the iterable object elements with a function. After mapping it collects
the values passed to the function if the function returns True.
2. filter objects are 1 time iterable objects
def f1(x):
if x%2==0:
return True
else:
return False
f1=filter(f1,range(1,11))
print("firstu timu=",list(f1))
print("secondu timu=",list(f1))
output:
[2, 4, 6, 8, 10]
print(list(filter(lambda x:x%2==0,range(1,11))))
output:
[2, 4, 6, 8, 10]
import functools
def f1(a,b):
return a*b
r1=functools.reduce(f1,range(1,6))
print(r1)
output:
120
Program-102(Wipro Task)
#s1="madhu123@gmail.com"
s1=input()
if '@' in s1 and '.' in s1:
part1=s1[0:s1.index('@')]
part2=s1[s1.index('@'):s1.index(".")]
part3=s1[s1.index(".")+1:None]
# print("part-1=",part1)
# print("part-2=",part2)
# print("part-3=",part3)
if part1.isalnum() and part1.islower() and part2.lower() in
['@gmail','@wipro','@yahoo'] and part3.lower()=="com":
print(f"{part1}:{part3}:Valid")
else:
print(f"{part1}:{part2}:Invalid")
else:
print(f"Invalid Input")
output:
madhutech@gmail.com
madhutech:com:Valid
Program-103(Wipro Task)
"""
input1:1w2i3p4r5o6
Option:0 or 1
if option is zero then we need to add the digits
"""
input1=input()
opt=int(input())
def fun1(n):
#n=678
#sum=6,13,21
while len(str(n))>1:
sum=0
#sum=2,3
for d in str(n):
#d=6
sum=sum+int(d)
n=sum
return n
if opt==0:
sum=0
for ch in input1:
if ch.isdigit():
sum=sum+int(ch)
print(fun1(sum))
else:
sum=0
for ch in input1:
if ch.isalpha():
sum=sum+ord(ch)
print(fun1(sum))
output:
1W2i3p4r5o6
1
7
Output:
1W2i3p4r5o6
0
3
Files
one.txt
file=open("emps.txt","w+")
file.write("1\tmadhu\t100000\n")
file.write("2\tshekar\t200000\n")
file.write("3\tkrishna\t300000\n")
file.seek(0)
print("Written data is")
print(file.read())
file.close()
file=open("one.txt","r+")
print("data existed in a file")
print(file.read())
file.write("5\tnarayana rao\t500000\n")
file.seek(0)
print("data exxisted in a file after read")
print(file.read())
output:
file1=open("histroy.jpg","rb")
file2=open("history2.jpg","wb")
file2.write(file1.read())
file2.close();
file1.close()
Program(109)
l1=[10,True,10+5j,100.50,"madhu",""]
print(all(l1))
print(any(l1))
l1=[1,2,3,4,5]
print("sum of l1:\t",sum(l1))
print("max of l1:\t",max(l1))
print("min of l1:\t",min(l1))
l1=[10,20,30,40,True,False]
print("sum of l1:\t",sum(l1))
l1=sorted((10,5,3,8,5,7))
print("l1=",l1)
l1=sorted((10,5,3,8,5,7),reverse=True)
print("l1=",l1)
e1=enumerate([10,20,30,40,50,60])
for i,v in e1:
print(i,v)
a,b,c,d=[10,20,30,40]
print(f"a:\t{a}")
print(f"b:\t{b}")
print(f"c:\t{c}")
print(f"d:\t{d}")
output:
a: 10
b: 20
c: 30
d: 40
Program-111(unpacking example)
l1=[10,20,30,40,50]
print("l1=",l1)
print("*l1=",*l1)
output:
l1= [10, 20, 30, 40, 50]
*l1= 10 20 30 40 50
def fun1(a,b,c,d):
print(f"a:\t{a}")
print(f"b:\t{b}")
print(f"c:\t{c}")
print(f"d:\t{d}")
l1=[10,20,30,40]
fun1(*l1)
fun1(**{"a":100,"b":100,"c":100,"d":100,})
output:
a: 10
b: 20
c: 30
d: 40
a: 100
b: 100
c: 100
d: 100
Program-114(list comprehension )
Example-116(generator comprehension)
Example-117(dictionary comprehension)
OOPS CONCEPT
class BuildingPlan:
city="Vijayawada"
def __init__(self):
#self=1002
self.kitchen=None
self.prayerRoom=None
self.br1=None
self.hall=None
def cooking(self):
print("We prepare food in kitchen")
def takeRest(self):
print("Take rest in bedroom")
def watchTV(self):
print("We watch tv in hall")
banubabyNilayam=BuildingPlan()
banubabyNilayam.cooking()
banubabyNilayam.takeRest()
output:
class Student:
college="MIC"
def __init__(this):
#this=2002
print("constructor....")
this.sno=None
this.sname=None
def display(this):#s1
#this=s1=2002
print("Object state.....")
print(f"this.sno={this.sno}")
print(f"this.sname={this.sname}")
s1=Student()
s1.sno=1
s1.sname="Bhanu"
s1.display()
output:
constructor....
Object state.....
this.sno=1
this.sname=Bhanu
class Emp:
company="TCS"
def __init__(self):
self.eid=None
self.ename=None
self.sal=None
def display(self):
#self=e2=1002
print("Object state....")
print(f"Eid:\t{self.eid}")
print(f"Ename:\t{self.ename}")
print(f"Sal:\t{self.sal}")
e1=Emp()
e2=Emp()
#e1 object initialization
e1.eid=1
e1.ename="Priya"
e1.sal=100000.00
e1.display()
e2.display()
output:
Object state....
Eid: 1
Ename: Priya
Sal: 100000.0
Object state....
Eid: 2
Ename: Shriya
Sal: 200000.0
class Emp:
company="TCS"
def __init__(self,eid,ename,sal):
#self=1002
#eid=1
#ename="madhu"
#sal=100000
self.eid=eid
self.ename=ename
self.sal=sal
def display(self):
#self=e3=3002
print("Object state....")
print(f"Eid:\t{self.eid}")
print(f"Ename:\t{self.ename}")
print(f"Sal:\t{self.sal}")
e1=Emp(1,"madhu",100000)
e2=Emp(2,"Shekar",200000)
e3=Emp(3,"GiriBabu",300000)
e1.display()
e2.display()
e3.display()
output:
Object state....
Eid: 1
Ename: madhu
Sal: 100000
Object state....
Eid: 2
Ename: Shekar
Sal: 200000
Object state....
Eid: 3
Ename: GiriBabu
Sal: 300000
Program-122(Example on single level inheritance and overriding)
class Bird:
def __init__(self,name,color,food):
self.name=name
self.color=color
self.food=food
def fly(self):
#self=parrot=1002
print(f"{self.name} can fly")
def eat(self):
print(f"{self.name} eats {self.food}")
def sing(self):
print(f"{self.name} can't sing")
def talk(self):
print(f"{self.name} can't talk like human")
class Parrot(Bird):
def talk(self):
print(f"{self.name} can talk like human")
class Bird:
def __init__(self,name,color,food):
self.name=name
self.color=color
self.food=food
def fly(self):
#self=parrot=1002
print(f"{self.name} can fly")
def eat(self):
print(f"{self.name} eats {self.food}")
def sing(self):
print(f"{self.name} can't sing")
def talk(self):
print(f"{self.name} can't talk like human")
class Parrot(Bird):
def talk(self):
print(f"{self.name} can talk like human")
class Ostritch(Bird):
def fly(self):
print(f"{self.name} fatty andeee can't fly andeeee")
ostr1.eat()
ostr1.talk()
ostr1.sing()
ostr1.fly()
output:
Indian Parrot eats Seeds & Gauva
Indian Parrot can talk like human
Indian Parrot can't sing
Indian Parrot can fly
Ostritch eats Insects
Ostritch can't talk like human
Ostritch can't sing
Ostritch fatty andeee can't fly andeeee
Program-124(program on overriding and calling it in child class)
class Base:
def __init__(self,a,b):
#self=1002
#a=100
#b=200
print("Base class constructor")
self.a=a
self.b=b
def display(self):
print("Base display....")
print(f"a:\t{self.a}")
print(f"a:\t{self.b}")
class Child(Base):
def __init__(self,a,b,c,d):
#self=1002
super().__init__(a,b)
#Base.__init__(self,a,b)
self.c=c
self.d=d
def display(self):
print("Child display....")
print(f"c:\t{self.c}")
print(f"d:\t{self.d}")
super().display()
c1=Child(100,200,300,400)
c1.display()
output:
Base class constructor
Child display....
c: 300
d: 400
Base display....
a: 100
a: 200
Program-125(Multi level inheritance)
class Base:
def __init__(this,a):
this.a=a
def display(this):
print(f"a:\t{this.a}")
class Child(Base):
def __init__(this,a,b):
super().__init__(a)
this.b=b
def display(this):
super().display()
print(f"b:\t{this.b}")
class SubChild(Child):
def __init__(this,a,b,c):
#super().__init__(a,b)
Child.__init__(this,a,b)
this.c=c
def display(this):
#super().display()
Child.display(this)
print(f"c:\t{this.c}")
sc=SubChild(1000,2000,3000)
sc.display()
output:
a: 1000
b: 2000
c: 3000
class One:
s=100
def __init_(self,a,b):
self.a=a
self.b=b
@staticmethod
def fun1():
print("s:\t",One.s)
@classmethod
def fun2(cls):
print("class method....")
print("type(cls):\t",type(cls))
print("cls contains info about '",cls.__name__,"' class")
@staticmethod
def add(a,b):
return a+b
def display(self):
print("a:\t",self.a)
print("b:\t",self.b)
# One.fun1()
# c=One.add(1000,2000)
# print("c:\t",c)
One.fun2()
Output:
class method....
type(cls): <class 'type'>
cls contains info about ' One ' class
class One:
def __init__(self,a,b,c):
self.__a=a
self.__b=b
self.c=c
def __fun1(self):
print("private function")
o1=One(10,20,30)
print("c:\t",o1.c)
# print("__a:\t",o1.__a)
# print("__b:\t",o1.__b)
o1.__fun1()
Exception Handling
print("c:\t",c)
print("end of the program")
output:
start of the program
a: 10
b: 0
Handling error......
c: 0
end of the program
rstream=None
try:
rstream=open("ExDemo1.py","r")
data=rstream.read()
print()
except FileNotFoundError as error:
print("Orai sachinodaaa leni file name istavaaaaa....")
print(error)
finally:
if rstream!=None:
rstream.close()
rstream=None
try:
rstream=open("ExDemo1.py","r")
data=rstream.read()
print()
except FileNotFoundError as error:
print("Orai sachinodaaa leni file name istavaaaaa....")
print(error)
finally:
if rstream!=None:
rstream.close()
class InvalidError(Exception):
pass
userid=input("Userid:")
pwd=input("Password:")
try:
if userid=="madhu" and pwd=="123456":
print("Welcome to MIC")
else:
raise InvalidError("Invalid User")
except InvalidError as ierror:
print(".......error........")
print(ierror)
print(".......error........")
Program-133(destructors example)
class Manishi:
def __init__(self):
print("He is Crying.............")
def __del__(self):
print("Relatives Crying....");
bujji_gadu=Manishi()
print("year-1")
print("year-2")
print("year-3")
print("year..")
print("year..")
print("Year-70")
del bujji_gadu
class FR:
def __init__(self,fileName):
self.file=open(fileName,"r")
print("a stream(file) is opened in constructor")
def display(self):
print(self.file.read())
def __del__(self):
self.file.close()
print("stream is closed in destructor...")
frObject=FR("emps.txt")
frObject.display()