0% found this document useful (0 votes)
9 views

Programs To Teach

The document provides examples of using print and input functions in Python. Program 1-5 demonstrate basic usage of print with strings, integers, and formatting. Programs 6-8 show how input takes user input as a string and it can be converted to other types. Later programs demonstrate arithmetic, relational, and conditional operators. Formatted string outputs are illustrated using old % formatting and new f-strings. The document serves as a tutorial on Python's core I/O functions and basic programming concepts.

Uploaded by

Rahul N
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Programs To Teach

The document provides examples of using print and input functions in Python. Program 1-5 demonstrate basic usage of print with strings, integers, and formatting. Programs 6-8 show how input takes user input as a string and it can be converted to other types. Later programs demonstrate arithmetic, relational, and conditional operators. Formatted string outputs are illustrated using old % formatting and new f-strings. The document serves as a tutorial on Python's core I/O functions and basic programming concepts.

Uploaded by

Rahul N
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Learn Through Programming

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:

print("Hello World", end="*")


output:
Hello World*

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.

What is the default value of keyword argument end?

Ans. New line(\n)


Explanation: If you don’t pass any argument to the keyword argument end while calling print function
then \n will be taken as default value.

If you want to stay on the same line after printing the given data (arguments) what should you have to
do?

Use end argument of print function and pass a string


Program-3

print("Hello World", end=None)


print("Okay")
output:
Hello World
Okay

What happens when we pass None to the end parameter?

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)

In the above example we have passed 2 arguments to the print function


1. first argument is string
2. second argument is integer i.e int object ‘a’ which contains 10
so print function prints the both arguments and moves the cursor to the new line

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

How many arguments we can pass to the print function?

We can pass zero or more aguments.

Program-6

s1 = input()
print("s1:\t", s1)
output:
madhu tech skills
s1: madhu tech skills

What is the use of input() function?

If you want to take the data from keyboard we have to call input function in python

Can an input function print the data?

1. Yes we can pass an argument to the input() function while calling it


2. if you pass argument it displays that argument just like print function and after printing the
given argument it waits there in the console monitor to take the data from keyboard.

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.

What Is the return type of the input() function?

Ans. string

What actually happens when we call the input function?

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

Program-8(how to read/take an int value from keyboard)

s1 = input("Enter int value:\t")


a = int(s1)
print("Type of s1:\t", type(s1))
print("s1:\t", s1)
print("Type of a:\t", type(a))
print("a:\t", a)

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

a = int(input("Enter int value:\t"))


print("Type of a:\t", type(a))
print("a:\t", a)

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)

a = int(input("Enter int value:\t"))


b = int(input("Enter int value:\t"))
r1 = a+b # addition
r2 = a-b # subtraction
r3 = a*b # multiplication
r4 = a/b # division
r5 = a//b # floor division
r6 = a % b # modulus division
r7 = a**b # exponentiation
print("r1:\t", r1)
print("r2:\t", r2)
print("r3:\t", r3)
print("r4:\t", r4)
print("r5:\t", r5)
print("r6:\t", r6)
print("r7:\t", r7)
output:
Enter int value: 10
Enter int value: 3
r1: 13
r2: 7
r3: 30
r4: 3.3333333333333335
r5: 3
r6: 1
r7: 1000

Program-11(example on relational operators)

a = int(input("Enter int value:\t"))


b = int(input("Enter int value:\t"))
r1 = a < b # lessthan
r2 = a <= b # lessthan or equals to
r3 = a > b # greater than
r4 = a >= b # greater than or equals to
r5 = a == b # double equals to
r6 = a != b # not equals to
print("r1:\t", r1)
print("r2:\t", r2)
print("r3:\t", r3)
print("r4:\t", r4)
print("r5:\t", r5)
print("r6:\t", r6)
output:
Enter int value: 10
Enter int value: 3
r1: False
r2: False
r3: True
r4: True
r5: False
r6: True

Program-12(program to find biggest among given 2 integers)

a = int(input("Enter int value:\t"))


b = int(input("Enter int value:\t"))
if (a > b):
print("a is bigger")
else:
print("b is bigger")

output:
Enter int value: 2
Enter int value: 10
b is bigger

Program-13

# program to check whether a person is eligible to vote or not


age = int(input("Enter you age:\t"))
if (age >= 18):
print("You are eligible to vote")
else:
print("You are not eligible to vote")

Program-14 example on nested if

# write a program whether a person is eligible to vote in india or


not
country = input("Enter your country:\t")
country = country.upper()
if (country == "BHARATH"):
age = int(input("Enter your age:\t"))
if (age >= 18):
print("You are eligible to vote")
else:
print("You are Not eligible to vote because you age is ",
age)
else:
print("You are not eligible to vote because you are not born in
bharath")

output-1:
Enter your country: bharath
Enter your age: 18
You are eligible to vote

Program-15: Another example on nested if to compare 3 int values

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

Program-16 (program on formatted string):

a = 100
print("a={a}") # output: a={a}
print(f"a={a}") # output: a=100
output:
a={a}
a=100

Program-17 (program on formatted string with a feature introduced in 3.6):

a = float(input("Enter float value:\t"))


b = float(input("Enter another float value:\t"))
c = a/b
print(f"{a}/{b}={c}")
d = a//b
print(f"{a}//{b}={d}")

output:
Enter float value: 10.60
Enter another float value: 2.00
10.6/2.0=5.3
10.6//2.0=5.0

Program-18(old way of formatting)

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

Program-19 formatting multiple values in old way

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

Program-20(old way of formatting a string)

a = float(input("Enter float value:\t"))


b = float(input("Enter another float value:\t"))
c = a+b
print("%f+%f=%f" % (a, b, c))
d = a-b
print("%f-%f=%f" % (a, b, c))

output:
Enter float value: 10
Enter another float value: 2
10.000000+2.000000=12.000000
10.000000-2.000000=12.000000

Program-21: Another example on old formatting method

a = complex(input("Enter complex value:\t"))


b = complex(input("Enter another complex value:\t"))
c = a+b
print("%s+%s=%s" % (a, b, c))
d = a-b
print("%s-%s=%s" % (a, b, c))
output:
Enter complex value: 10
Enter another complex value: 20+5j
(10+0j)+(20+5j)=(30+5j)
(10+0j)-(20+5j)=(30+5j)

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.

Program-22 Formatting a string using format function

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

Program-23 Formatting a string using format function

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

1. Logical operators are used to combine conditional statements:


2. logical operators are also called as boolean operators because these operators performs
operation on only Boolean values.

Program-24(program on logical and operator)

# logical and operator gives us True if both operands are true,


otherwise it gives us False
# logical and operator returns false without checking 2nd condition
if the first condition is false
r1 = True and True
r2 = True and False
r3 = False and True
r4 = False and False

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

Program-25(compare three numbers using logical and operator)

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

Program-26(example on logical or operator):

#logical or operator gives(returns) us True if any one among two


operands is True otherwise it returns(gives) us False
#logical or operator returns us True without checking second
condition if the first condition is True
r1 = True or True
r2 = True or False
r3 = False or True
r4 = False or False
print("r1:\t", r1)
print("r1:\t", r2)
print("r3:\t", r3)
print("r4:\t", r4)

output:
r1: True
r1: True
r3: True
r4: False

Program-27(example on logical or operator):

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")

Program-28(example on displaying specified character of a string)

name = "Madhu Tech Skills"


# printing 6th index character from name
print(name[6])
# printing 0th index character from name
print(name[0])
# printing last index character from name
print(name[-1])
output:
T
a
s

Program-29(program to convert a string into upper case)

name1 = "Madhu Tech Skills"


name2 = name1.upper()
# upper method doesn't modify the name1 string but it returns a
# new string object which contains upper case letters
# Note: strings are immutable objects
print("name1:\t", name1) # check it won't get modified
print("name2:\t", name2) # new string returned by upper() function
Program-30(program to convert a string into lower case)

name1 = "Madhu Tech Skills"


name2 = name1.lower()
# lower function doesn't modify the name1 string but it returns a
# new string object which contains lower case letters
# Note: strings are immutable objects
print("name1:\t", name1) # check it won't get modified
print("name2:\t", name2) # it is a new string returned by lower()
function

Program-31(program to check whether the given character is vowel or not)

inputString = input("Enter any string:\t")


# getting first character from input string and converting it into
upper case and storing it in a variable called ch
ch = inputString[0]
ch1 = ch.upper()
if ch1 == "A" or ch1 == "E" or ch1 == "I" or ch1 == "O" or ch1 ==
"U":
print(f"{ch} is Vowel")
else:
print(f"{ch} is not a Vowel")
output:
Enter any string: B
B is not a Vowel

output-1:
Enter any string: a
a is Vowel

Program-32(example to print substring of a string using slicing operator)


name = "Madhu Tech Skills"
# by using slicing we can sequence or pattern of characters from a
string
# [start_index:stop_index+1:stepvalue]
s1 = name[6:10:1] # getting Tech from string name
print("name[6:10:1]:\t", s1)
s2 = name[0:5:1] # getting Madhu from string name
print("name[0:5:1]:\t", s2)
output:
name[6:10:1]: Tech
name[0:5:1]: Madhu

Program-33 (string slicing) getting all the characters in different ways

name = "Madhu Tech Skills"


# by using slicing we can sequence or pattern of characters from a
string
# [start_index:stop_index+1:stepvalue]
print("name:\t", name)
print("name[0:17:1]:\t", name[0:17:1]) # getting all the characters
print("name[0:None:1]:\t", name[0:None:1]) # getting all the
characters
print("name[None:None:1]:\t", name[None:None:1]) # getting all the
characters
print("name[None:None]:\t", name[None:None]) # getting all the
characters
print("name[:None]:\t", name[:None]) # getting all the characters
print("name[:]:\t", name[:]) # getting all the characters
print("name[::1]:\t", name[::1]) # getting all the characters
output:
name: Madhu Tech Skills
name[0:17:1]: Madhu Tech Skills
name[0:None:1]: Madhu Tech Skills
name[None:None:1]: Madhu Tech Skills
name[None:None]: Madhu Tech Skills
name[:None]: Madhu Tech Skills
name[:]: Madhu Tech Skills
name[::1]: Madhu Tech Skills
Program-34(getting elements in reverse order using slicing)

name = "Madhu Tech Skills"


# by using slicing we can sequence or pattern of characters from a
string
# [start_index:stop_index+1:stepvalue]

print("name[16:None:-1]:\t", name[16:None:-1]) # total string in


reverse order
# total string in reverse order
print("name[None:None:-1]:\t", name[None:None:-1])
print("name[::-1]:\t", name[::-1]) # total string in reverse order
print("name[-1:-18:-1]:\t", name[-1:-18:-1]) # total string in
reverse order
print("name[16:-18:-1]:\t", name[16:-18:-1]) # total string in
reverse order
output:
name[16:None:-1]: sllikS hceT uhdaM
name[None:None:-1]: sllikS hceT uhdaM
name[::-1]: sllikS hceT uhdaM
name[-1:-18:-1]: sllikS hceT uhdaM
name[16:-18:-1]: sllikS hceT uhdaM

Program-35(program to get characters using different set values in slicing)

name = "Madhu Tech Skills"


print("name[None:None:2]:\t", name[None:None:2])
print("name[::3]:\t", name[::3])
output:
name[None:None:2]: MduTc kls
name[::3]: MhThkl

RANGE AND FOR LOOP


1. Range class is used to generate a sequence/pattern of numbers
2. For loop is used to get the elements from an iterable object.

Note: collection objects are also called as collection literals and all the collection or sequence objects are
also called as iterable objects.

List of iterable objects

1. string
2. range
3. list
4. tuple
5. set
6. frozenset
7. dict
etc….

Program-36(example on range)

# range class is used to generate sequence of numbers


# range class constructor can take 3 arguments
# 1. start value 2. stop value 3. step value
r_obj = range(11)
# To the ranage class constructor i have passed only stop value so 0
to 10 numbers will be generated
# the default start value is 0
# the default step value is 1
print("elements existed in range object")
for ele in r_obj:
print(ele)

output:
elements existed in range object
0
1
2
3
4
5
6
7
8
9
10

Program-37(program to generate 1 to n natural numbers using range class constructor)

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

Program-38(Program to generate n to 1 natural numbers using range class constructor)

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

Program-39(Program to generate 1 to n even numbers using range class constructor)

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

Program-40(Program to generate 1 to n odd numbers using range class constructor)

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

Program-41(Program to generate n to 1 odd numbers using range class constructor)

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

Program-42(Program to generate n to 0 even numbers using range class constructor)

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

Program-43(program to find factors of a given number)

n = int(input("n:\t"))
print(f"Factors of {n} Are:")
for i in range(1, n+1):
if (n % i == 0):
print(i)

Note: in the above program we are checking whether I is the factor


of n or not if I is factor then we are printing it.

Program-44(Write a program to find factors count of a given number)

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

print(f"Factors count of {n} Is {count}")

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")

Program-47(Write a program to find whether the given number is prime or not)

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

Program-48(primr or not with different logic(bettern than above)

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")

Program-49 (program to find prime better logic than above program )


n=int(input("n:\t"))
flag=True
if n in [0,1]:
flag=False
else:
for i in range(2, (n//2)+1 ):
if(n%i==0):
flag=False
break;
if flag:
print(f"{n} is Prime")
else:
print(f"{n} is Not a Prime")

Program-50 ( to find out factorial of a given number)

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

Program-51(Program to print digits of a given number)

# 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

Program-52 (program to reverse a given number without converting into a string)


n=int(input("n:"))
rev=0
while n>0:
r=n%10
rev=rev*10+r
n=n//10
print("reverse of number is ",rev)
output:

Porgram-53( program to find whether the given number is Armstrong or not)

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

Program-54 (to print the belo pattern)

*
**
***
****
*****

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-56: (Program to print the below pattern)

*
**
***
****
*****
Program

n=int(input("n:\t"))
#n=5
#i=1
for i in range(1,n+1,1):
print( (" "*(n-i))+("* "*i) )

Program-57(progrra to print below pattern)

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])

(Program:59) Write a program to print the below pattern

Enter a number between(2,27): 5


A
AB
ABC
ABCD
ABCDE

alphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
n=int(input("entere a number between(2,27):\t"))
for i in range(1,n+1):
print(alphabets[0:i])

Program-60: (same as above problem by using nested for loops)

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: ()

Type of t1: <class 'int'>

Type of t1: <class 'tuple'>

Program-62(creating tuples with elements)

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'>

Program-63(program on tuples where we are using index and count functions)

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

Program-64(Program to sort tuple by using sorted function)

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:

Program-65(Program to create an empty set)

s1={}#dictionary will be created


s2=set() #set will be created
print("Type of s1:\t",type(s1))
print("Type of s2:\t",type(s2))
output

Type of s1: <class 'dict'>


Type of s2: <class 'set'>

Program66(Error while adding mutable object to set)

s1={10,20,30,"madhu",10+5j,[1,2,3,4,5]}#we will get an error because we are


adding mutable to set
print("Type of s1:\t",type(s1))
output:
s1={10,20,30,"madhu",10+5j,[1,2,3,4,5]}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unhashable type: 'list'

Program-67(set functions usage(copy,add,pop,remove,clear)

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()

Program-68(union() and update() function usage on set)


s1={10,20,30,40,50}
s2={10,30,40,60,70}
s3=s1.union(s2)
print("s1:\t",s1)
print("s2:\t",s2)
print("s3:\t",s3)
s1.update(s2) #union_update
print("s1:\t",s1)
output:

s1: {50, 20, 40, 10, 30}

s2: {70, 40, 10, 60, 30}

s3: {70, 40, 10, 50, 20, 60, 30}

s1: {70, 40, 10, 50, 20, 60, 30}

Program-69(Program on intersection and intersection_update)

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: {50, 20, 40, 10, 30}

s2: {70, 40, 10, 60, 30}

s3: {40, 10, 30}

s1: {40, 10, 30}

Program-70(program on difference and difference_update methods of set class)

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: {50, 20, 40, 10, 30}

s2: {70, 40, 10, 60, 30}

s3: {50, 20}

s1: {50, 20}

Program-71(program on symmetric_diference and symmetric_diference_update function

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: {50, 20, 40, 10, 30}

s2: {70, 40, 10, 60, 30}

s3: {50, 20, 70, 60}

s1: {50, 20, 70, 60}

Program-72(Example on isDisjoint(), subset(), superset())

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)

Program-73(example on dictionaries with update (),pop(),popitem() and get()

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'}

Program-74(Porgram on keys() and values() methods of dict class)

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

Program(75) creating a new dictionary with keys using fromkeys() method

Students1=dict.fromkeys(range(1,101))
Students2=dict.fromkeys(range(1,101), "hello")

print(students1)
print(students1)

Program-76(usage of set default function)

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}}

Program-77(usage of items function of dict class)

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')

Program-77(unpacking while iterating dict_items class object)

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

Program-79(example on frozen 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)

add() #function calling statement


output:
300

Program-81: (another example)

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

Program-82(Another program on functions with parameters)

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

Program-83(function with parameters and with return value)

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

Program-84(program on required and default arguments)

def add(a,b): #here a,b are required args


print(f"{a}+{b}={a+b}")

def sub(a=0,b=0): #a,b are default arguments


print(f"{a}-{b}={a-b}")

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:

Program-86(Variable length arguments and packing)

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)

Program-80(Example on Nested functions)

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

Program-89(Program on lambda functions or anonymous functions)

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

Program-90(creating lambda function with in parenthesis in a function call)

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)

Example-92 (on unpacking)

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)

Program-94(UnPacking a dictionary and list)


def student_result(sno,sname,c,cpp,java,python,oracle):
print("Student details")
print("Sno:\t",sno)
print("Sname:\t",sname)
print("c:\t",c)
print("cpp:\t",cpp)
print("java:\t",java)
print("python:\t",python)
print("oracle:\t",oracle)

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

Program-95(program on map usage)

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>

using for loop...........

1 4 9 16 25 36 49 64 81 100

Program-96(program to split method usage of a str class)

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]

Program-98(writing same code in single line)

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

Program-99(Example on fliter usage)

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]

Program-100(Same as above example written in singl line)

print(list(filter(lambda x:x%2==0,range(1,11))))
output:
[2, 4, 6, 8, 10]

Program-101(reduce function usage of functools module)

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

Program-104(to write the data to a file)


#if we open a file in write mode, a new file will be created if the file is not
existed
file=open("one.txt","w")
file.write("Orai Bangarraju Last Bench Bangaram...\n")
file.write("Next Nuvvey...\n")
file.close()

one.txt

Orai Bangarraju Last Bench Bangaram...


Next Nuvvey...

Program-105(Program to read the data from a file)


file=open("one.txt","r")
#we have to give the already existed file name when you are opening a file in
read mode
data=file.read()
print("data=",data)
file.close()

Program-106 to write and read using WritPlusmode

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()

Program-107 to read and write using ReadPlus Mode

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:

Program-108(Reeading and writing binary file)

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)

Program-110(UnPacking Basic example)

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

Program-112 (Unpacking example)

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-113(list comprehension example)

l1=[a**2 for a in range(1,11)]


print(f"l1={l1}")
output:
l1=[1, 4, 9, 16, 25, 36, 49, 64, 81, 100

Program-114(list comprehension )

l1=[a**2 for a in range(1,11) if a%2==0]


print(f"l1={l1}")
output:
l1=[4, 16, 36, 64, 100]
Example-115 (set comprehension example)

s1={a**2 for a in range(1,11) if a%2==0}


print(f"s1={s1}")
output:
s1={64, 100, 4, 36, 16}

Example-116(generator comprehension)

g1=(a**2 for a in range(1,11) if a%2==0)


print(f"Type of g1={type(g1)}")
print(f"g1={g1}")
print(f"tuple(g1)={tuple(g1)}")
output:
Type of g1=<class 'generator'>
g1=<generator object <genexpr> at 0x0000012DFA358380>
tuple(g1)=(4, 16, 36, 64, 100)

Example-117(dictionary comprehension)

d1={a:a**2 for a in range(1,11)}


print(f"Type of d1={type(d1)}")
print(f"d1={d1}")
output:
Type of d1=<class 'dict'>
d1={1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

OOPS CONCEPT

Example-118(class object example)

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:

We prepare food in kitchen

Take rest in bedroom

Program-119(class object demo)

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

Example-120(multiple objects creation)

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

#e2 object initialization


e2.eid=2
e2.ename="Shriya"
e2.sal=200000.00

e1.display()
e2.display()

output:
Object state....
Eid: 1
Ename: Priya
Sal: 100000.0
Object state....
Eid: 2
Ename: Shriya
Sal: 200000.0

Program-121(Parameterized constructor example)

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")

p1=Parrot("Indian Parrot","Yellow","Seeds & Gauva")


p1.eat()
p1.talk()
p1.sing()
p1.fly()
output:

Indian Parrot eats Seeds & Gauva

Indian Parrot can talk like human

Indian Parrot can't sing

Indian Parrot can fly

Program-123(program on hierarchical inheritance)

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")

p1=Parrot("Indian Parrot","Yellow","Seeds & Gauva")


ostr1=Ostritch("Ostritch","Black & White","Insects")
p1.eat()
p1.talk()
p1.sing()
p1.fly()

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

Program-126(Program on static and class methods)

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

Program-127(example on private fields and methods)

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

Program-128(Example on try and except block)

print("start of the program")


a=int(input("a:\t"))
b=int(input("b:\t"))
c=0
try:
c=a/b
except:
print("Handling error......")

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

Program-129(multiple except blocks and finally block usage)

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()

Program-130(finally block usage good example)

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()

Program-131(usage of raise keyword throwing exception by the user)

print("start of the program")


a=b=c=0
try:
a=int(input("a:\t"))
b=int(input("b:\t"))
if b==0:
raise ZeroDivisionError("Nee lathkoor mokhamla naaa cheppu, b value zero
istavaaa raaa nuvvuu")
c=a/b
except ValueError as ve:
print("Choosukunaa panllaaaaa input icheytappudu")
except ZeroDivisionError as ze:
print(ze)
finally:
print("finally.........")
print("c:\t",c)
print("end of the program")

Program-132 (program to create and raise user-defined exceptions)

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

Program(134) example on constructor and destructor

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()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy