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

Python Book

The document provides an overview of Python programming, covering topics such as data types, control constructs, methods, and object-oriented programming. It explains the differences between Python and other programming languages, the features of Python, and the various data types available in Python including basic and advanced types. Additionally, it discusses concepts like type casting, lists, tuples, sets, and dictionaries in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Book

The document provides an overview of Python programming, covering topics such as data types, control constructs, methods, and object-oriented programming. It explains the differences between Python and other programming languages, the features of Python, and the various data types available in Python including basic and advanced types. Additionally, it discusses concepts like type casting, lists, tuples, sets, and dictionaries in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

INDEX

Topic No. Topics Page No.


01 Python Overview…………………………………………… 1
02 Data Types…………………………………………………. 4
03 Control Construct…………………………………………... 13
04 Methods……………………………………………………. 17
05 Strings……………………………………………………… 27
06 Object Orientation .....…………………………………....... 32
07 Inheritance…………………………………………………. 36
08 Static……………………………………………………….. 41
09 Constructor………………………………………………… 44
10 Access Specifier…………………………………………… 47
11 Polymorphism……………………………………………… 50
12 Magic Methods…………………………………………….. 53
13 Abstraction………………………………………………… 58
14 Operator Overloading……………………………………… 60
15 Exception Handling………………………………………… 62
16 File Handling……………………………………………….. 65
17 Django………………………………………………………. 66
18 Programs on Python ……………………………………….. 68
www.kodnest.com

TOPIC 1
PYTHON OVERVIEW
1. What is the difference between a compiler and an interpreter?
The interpreter converts one statement at a time into machine-level language, where as the compiler
converts the complete code at a time into machine-level language.

2. Is Python dynamically typed language or statically typed language?


Python is a dynamically typed language because it checks the type of variables during run-time.

3. What is dynamically typed language?


Dynamically typed languages are such languages that check the type of variables during the run-time.
Few dynamically typed languages are Python, JavaScript, Ruby, etc.

4. What are the applications of the Python language?


Python has a simpler and easy-to-learn syntax. It may look similar to English. The community of
developers for Python is enormous.
Few applications of Python are:
1. To create web applications.
2. To create a console-based applications.
3. To create Desktop GUI applications.
4. To develop the software.
5. In the field of Machine Learning.
6. In the field of Automation.
7. In the field of Data Science.

5. What is Python?
Python is an interpreted, high-level, general-purpose programming language.
It has concise syntax compared to Java, and C. Python was invented in 1991 by developer Guido Van
Rossum. The name of the Python was kept after the television program Monty Python's Flying Circus.
As a general-purpose language, it is used to build almost any type of application with the correct
tools/libraries.

6. What is an Interpreted language?


An Interpreted language is such a language that executes the statements line by line using an
interpreter language processor. Few interpreted languages are Python, JavaScript, R, PHP, etc.

7. What is the use of self?


The self is a variable that contains the memory address of the instance of the class. We need not pass
anything to this variable.

8. Explain the difference between statically typed language and dynamically typed language?
The statically typed language is a language in which the programmer assigns the data type for the
variable, and the variable type is known at the compile time.
E.g., C, C++, Java.

In a dynamically typed language, the data type of a variable is assigned at run-time based on the
variable's value.
E.g., Python, Ruby, and JavaScript.

#Code with KodNest Page | 1


Topic 1 : Python Overview

9. What is the difference between C and Python?


The differences between C and Python are as follows:

C Python

C is a procedural language. Python is a scripting, procedural, object-


oriented language.
C is faster in execution compared to Python is slower compared to C.
Python.
C is statically typed language. Python is dynamically typed language.

C makes use of pointers. Python does not use pointers.

C have switch statement. Python does not have switch statement.

C has for loop, while loop, do-while loop. Python has for loop and while loop.

C does not have garbage collector. Python have garbage collector.

In C, indentation is not needed. In Python, indentation is needed to


represent a block of statements.

10. What is the difference between Java and Python?


The differences between Java and Python are as follows:

Java Python

Java is an object-oriented language. Python is a scripting, procedural, object-


oriented language.
Java contains more number of lines for Python contains less number of lines
program. compared to Java.

Java is statically typed language. Python is dynamically typed language.

Java has Java Virtual Machine for Python has Python Virtual Machine for
memory allocation, executing the java memory allocation, executing the java
programs, etc. programs, etc.

Java has switch statement. Python does not have switch statement.

Java has for loop, while loop, do-while Python has for loop and while loop.
loop.
In Java, indentation is not needed. In Python, indentation is needed to
represent the block of statements.

11. What is PVM?


PVM stands for Python virtual Machine. It is used to convert bytecodes into machine-level
language. It also provides the programming environment for python programming language.

Page | 2 #Code with KodNest


www.kodnest.com

12. What are the features of Python?


The following are few features of Python:
1. It is simple.
2. It is easy to learn.
3. It is a high-level language.
4. It is dynamically typed language.
5. It is platform independent.
6. It is open source.
7. It is portable.
8. It can be used as scripting, procedural and object-oriented language.

#Code with KodNest Page | 3


Topic 2 : Data Types

TOPIC 2
DATA TYPES
1. What are the basic data types in Python?
There are five data types in Python, they are:
int, float, bool, str, complex.
1. int data type is used to store integer numbers.
2. float data type is used to store real numbers.
3. bool data type is used to store Boolean values.
4. str data type is used to store string values.
5. complex data type is used to store complex numbers.

2. What are the advanced data types in Python?


There are four advanced data types in Python, they are:
list[], tuple(), set{}, dict{k,v}.

3. Which method is used to find the type of variable?


The type() is used to find the type of a variable.

4. What are the variables in Python?


A variable is a name given to the location in memory. We use variables to save and restore values
or the results of calculations. As Python is dynamically typed language, the programmer does not
need to mention the type of variable. Rather the type of variable will be assigned during the
runtime.

5. Write a note on the data types in Python and how Python decides the data type for the
variable?
There are five basic and four advanced datatypes in Python.
Basic data types- int, float, bool, str, complex.
Advanced data types- list[], tuple(), set{}, dict{k,v}.
Python decides the data type based on the value stored in the variable during the runtime.

Example:-
i = 100, here integer value 100 is stored in variable i. Hence Python interpreter will decide on
variable i as an int type variable.
i = 10.88, here real number value 10.88 is stored in variable i. Hence Python interpreter will
decide on variable i as a float type variable.
i = True, here boolean value is stored in variable i. Hence Python interpreter will decide on
variable i as a bool type variable.
i ='KodNest', here string value is stored in the variable i. Hence Python will decide on variable i
as str type variable.

6. Write a note on the declaration of string in Python?


String or character in Python is declared using:
One single quotes. Eg: 'K' or 'KodNest'
Triple single quotes. Eg: '''K''' or '''KodNest'''
One Double quotes. Eg: "K" or "KodNest"
Triple Double quotes. Eg: """K""" or """KodNest""".

Page | 4 #Code with KodNest


www.kodnest.com

7. Explain int datatype?


The int data type is used to store positive or negative whole numbers in Python.

Example:-
a=2
print(a, "is of type", type(a))

Output:-
2 is of type int

8. Explain float datatype?


The float data type is used to store real number values in Python.

Example:-
b = 1.5
print(b, "is of type", type(b))

Output:-
1.5 is of type float

9. Explain bool datatype?


The bool data type is declared with the bool keyword and can only store the values True or False.

Example:-
x = True
print(x)
print(type(x))

Output:-
True
bool

10. Explain string datatype?


The string is a collection of one or more characters put in a quotation mark, double-quotes, or triple
quotes. It is represented using an str class.

Example1:-
string1= "Welcome To KodNest."
print(string1)

Output:-
Welcome To KodNest.

Example2:-
a = """KodNest!!"""
print(a)

Output:-
KodNest!!

Example3:-
a = '''KodNest!!!'''
print(a)

Output:-
KodNest!!!

#Code with KodNest Page | 5


Topic 2 : Data Types

11. Explain complex datatype?


The complex data type is used to represent the complex numbers. It is specified as
(real part)+(imaginary part) j.

Example:-
x=4+5j
print(x)
print(type(x))

Output:-
4+5j
complex

12. What is Type casting?


Type casting is the process of converting the value of one data type (integer, string, float, etc.) to
another data type. It is also known as type conversion.
Python has two types of type conversion.
1. Implicit Type Conversion
2. Explicit Type Conversion

13. Explain Implicit type casting?


Implicit type casting is the process of converting one data type into another data type
automatically. This process doesn't need any programmer involvement.

Example:-
a = 123
b = 1.23
sum = a + b
print("datatype of a",type(a))
print("datatype of b:",type(b))
print("Value of sum:",sum)
print("datatype of sum:",type(sum))

Output:-
datatype of a <class 'int'>
datatype of b: <class 'float'>
Value of sum: 124.23
datatype of sum: <class 'float'>

14. What are the common built-in data types in Python?


There are several built-in data types in Python. Although Python doesn't require data types to be
defined explicitly during variable declarations, type errors are likely to occur if the knowledge of
data types and their compatibility with each other are neglected. Python provides type() and
isinstance() functions to check the type of these variables. These data types can be grouped into
the following categories:
int data type : Stores integer literals including hex, octal and binary numbers as integers.
float data type: Stores literals containing decimal values and/or exponent signs as floating point
numbers.
complex data type: Stores complex numbers in the form (A + B j) and has attributes: real and
imaginary values.
bool data type: Stores boolean value i.e. True or False.

15. Explain list[] datatype in Python?


A list[] datatype in Python is used to store the sequence of various types of data. Python lists are
mutable. It means we can modify it's element after it is created. A list in Python can store both

Page | 6 #Code with KodNest


www.kodnest.com

homogeneous and heterogeneous type of data. The items in the list are separated with the comma (,)
and enclosed with the square brackets [].

Example 1:-
l1 = ["Rahul", 102, "Bangalore"]
print(l1)
print(type(l1))

Output:-
['Rahul', 102, 'Bangalore']
<class 'list'>

Example 2:-
l2 = [10, 2, 30, 4, 50, 6]
print(l2)
print(type(l2))

Output:-
[10, 2, 30, 4, 50, 6]
<class 'list'>

16. What are the characteristics of list[] datatype in Python?


The characteristics of list[] datatype in Python are as follows:
1. The lists are an ordered collection of data.
2. The element of the list can access by index.
3. The lists are the mutable type of data.

17. Explain the tuple() datatype in Python?


In Python, tuple() is used to store the sequence of immutable items or objects. Once the value of the
items are stored in the tuple then it cannot be changed. Tuples are represented using parenthesis ( ).

Example:-
t2 = ("Apple", "Banana", "Orange")
print(t2)
print(type(t2))

Output:-
('Apple', 'Banana', 'Orange')
<class 'tuple'>

18. Explain set{} datatype in Python?


The set() datatype in Python, is the collection of the unordered items. Each element in the set must
be unique. The set data type doesn't allow the duplicate elements. Sets are mutable which means we
can modify it after its creation.
Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we cannot
directly access any element of the set by using the index. However, we can print them all together, or
we can get the list of elements by looping through the set.
The set can be created by enclosing curly braces {}. Python also provides the set() method, which can
be used to create the set by the passed sequence.

Example:-
s = {"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}
print(s)
print(type(s))

#Code with KodNest Page | 7


Topic 2 : Data Types

Output:-
{'thursday', 'friday', 'monday', 'sunday', 'wednesday', 'saturday', 'tuesday'}
<class 'set'>

19. Explain dict{} data type in Python?


In Python, dict{} data type is used to create the Dictionary. It is used to store the data in a key-
value pair format. It can simulate the real-life data arrangement where some specific value exists
for some particular key.

Example:-
emp = {"Name": "Rahul", "Age": 29, "salary":80000,"Company":"KodNest"}
print(emp)
print(type(emp))

Output:-
{'Name': 'Rahul', 'Age': 29, 'salary': 80000, 'Company': 'KodNest'}
<class 'dict'>

20. What is the difference between the list and tuple datatype in Python?
The List and Tuple are both sequence data types that can store a collection of items or objects in
Python. The objects stored in both sequences can have different data types. Lists are represented
with square brackets ['sara', 6, 0.19], while tuples are represented with parentheses ('ansh', 5,
0.97).
The main difference between list and tuple datatype in Python is that while lists are mutable,
tuples are immutable objects. This means that lists can be modified, appended or sliced but tuples
remain constant and cannot be modified in any manner.

Example:-
my_tuple = ('sara', 6, 5, 0.97)
my_list = ['sara', 6, 5, 0.97]
print(my_tuple[0]) # output => 'sara'
print(my_list[0]) # output => 'sara'
my_tuple[0] = 'ansh' # modifying tuple => throws an error
my_list[0] = 'ansh' # modifying list => list modified
print(my_tuple[0]) # output => 'sara'
print(my_list[0]) # output => 'ansh'

21. What are mutable and immutable data types?


Mutable data types are such data types which can be changed after creating them. The mutable
data types in Python are list, set, and dict.
Immutable data types are such data types which can't be changed after creating them. The
immutable data types in Python are str, tuple.

22. Explain some methods of the list.


Few methods of the list are as follows:-
1. append():- append() is used to add an element to the list. It adds the element to the end of the
list.

Example:-
a = [10,20,30,40,50]
a.append(99)
print(a)

Output:-
[10, 20, 30, 40, 50, 99]

Page | 8 #Code with KodNest


www.kodnest.com

2. pop():- pop() is used to remove an element from the list. It will remove the last element if we don't
provide any index as an argument or remove the element at the index if we provide an argument.

Example:-
a = [10,20,30,40,50]
print(a)
a.pop()
print(a)
a.pop(1)
print(a)

Output:-
[10, 20, 30, 40, 50]
[10, 20, 30, 40]
[10, 30, 40]

3. remove():- remove() is used to remove an element from the list. We need to provide the element
as an argument that we want to remove from the list. It removes the first occurrence of the element
from the list.

Example:-
a=[10,20,30,40,50]
print(a)
a.remove(20)
print(a)
a.remove(40)
print(a)

Output:-
[10, 20, 30, 40, 50]
[10, 30, 40, 50]
[10, 30, 50]

4. sort():- sort() is used to sort the list in ascending or descending order.

Example:-
a=[40,20,30,10,50]
print(a)
a.sort()
print(a)
a.sort(reverse=True)
print(a)

Output:-
[40, 20, 30, 10, 50]
[10, 20, 30, 40, 50]
[50, 40, 30, 20, 10]

5. reverse():- reverse() is used to reverse the elements present in the list.

Example:-
a=[10,20,30,40,50]
print(a)
a.reverse()
print(a)

#Code with KodNest Page | 9


Topic 2 : Data Types

Output:-
[10, 20, 30, 40, 50]
[50, 40, 30, 20, 10]

23. Explain some methods of the dict.


Few methods of dict are as follows:-
1. items():- items() is used to return key:value pairs of dictionaries as a list of tuples.

Example:-
a = {1:'Rahul', 2: 'Raju', 3: 'Roshan'}
print(a.items())

Output:-
dict_items([(1, 'Rahul'), (2, 'Raju'), (3, 'Roshan')])

2. pop():- pop() is used to remove the key:value pair from the dictionary. It accepts the key as an
argument and removes it from the dictionary.

Example:-
a = {1:'Rahul', 2: 'Raju', 3: 'Roshan'}
print(a)
a.pop(2)
print(a)

Output:-
{1: 'Rahul', 2: 'Raju', 3: 'Roshan'}
{1: 'Rahul', 3: 'Roshan'}

3. clear():- clear() is used to removes all key:value pair from the dictionary.

Example:-
a = {1:'Rahul', 2: 'Raju', 3: 'Roshan'}
print(a)
a.clear()
print(a)

Output:-
{1: 'Rahul', 2: 'Raju', 3: 'Roshan'}
{}

4. update():- update() is used to add key:value pair in the dictionary.

Example:-
a = {1:'Rahul', 2: 'Raju', 3: 'Roshan'}
print(a)
a.update({4:'Mohan'})
print(a)

Output:-
{1: 'Rahul', 2: 'Raju', 3: 'Roshan'}
{1: 'Rahul', 2: 'Raju', 3: 'Roshan', 4: 'Mohan'}

Page | 10 #Code with KodNest


www.kodnest.com

5. values():- values() is used to return the values of a key:value pair from the dictionary.

Example:-
a = {1:'Rahul', 2: 'Raju', 3: 'Roshan'}
print(a)
print(a.values())

Output:-
{1: 'Rahul', 2: 'Raju', 3: 'Roshan'}
dict_values(['Rahul', 'Raju', 'Roshan'])

24. Explain some methods of the tuple.


Few methods of tuple are as follows:-
1. count():- count() is used to return the count of an element in a tuple.

Example:-
tup = (10,20,30,10,40,50,10)
print(tup.count(10))

Output:-
3

2. index():- index() is used to return the first occurrence of an element in a tuple.

Example:-
tup = (10,20,30,10,40,50,10)
print(tup.index(10))

Output:-
0

3. sorted():- sorted() is used to sort the elements present in the tuple.

Example:-
tup = (100,50,150,25,125,75,175)
print(sorted(tup))

Output:-
[25, 50, 75, 100, 125, 150, 175]

4. len():- len() is used to return the number of elements present in a tuple.

Example:-
tup = (100,50,150,25,125,75,175)
print(len(tup))

Output:-
7

5. min():- min() is used to return the minimum value present in the tuple.

Example:-
tup = (100,50,150,25,125,75,175)
print(min(tup))

Output:-
25
#Code with KodNest Page | 11
Topic 2 : Data Types

6. max():- max() is used to return the maximum value present in the tuple.

Example:-
tup = (100,50,150,25,125,75,175)
print(min(tup))

Output:-
175

25. What is an Iterator?


An iterator is an object used to iterate over iterable objects like lists, tuples, dicts, and sets. The
iterator object is initialized using the iter() method. It uses the next() method for iteration.

26. What are a few iterators available in Python?


The built-in iterators are present in the module "itertools".
Some useful Iterators:-
1. accumulate(iter,func):-This iterator accepts two arguments, one as iterable target and the
second as function.
2. chain(iter1,iter2...):-This function is used to print all the values in iterable targets one after
another mentioned in its arguments.
3. chain.from_iterable():-This function is implemented similarly to a chain(), but it accepts a list
of lists or any other iterable item.
4. filterfalse(func,seq):- This iterator prints only values that return false for the passed function.

Page | 12 #Code with KodNest


www.kodnest.com

TOPIC 3
CONTROL CONSTRUCT
1. Does Python have switch statements?
No, Python doesn't have switch statements. Instead of switch, if-elif-else control construct can be
used.

2. How do you implement the functionality of switch statements in Python?


We can implement the functionality of switch statements using if-elif-else control constructs.

3. When is the code in else executed with while and for loops?
The code inside the else block with while and for loops is executed after executing all iterations. And
the code inside the else block doesn't execute when we break the loops.

4. Explain if control construct in python.


The if statement is a conditional control construct which is used for conditional branching.

Syntax:-
if condition:
statement_of_if_block

Example:-
x=4
if x<=5:
print("x is less than 5")

Output:
x is less than 5

5. Explain the if-else control construct in python?


The if statement tells that if a condition is true it will execute a block of statements and if the condition
is false, it doesn't executes the if block. We can use the else statement with the if statement to execute
a block of code when the if condition is false.

Syntax:-
if (condition):
# Executes this block if condition is true
else:
# Executes this block if condition is false

Example:-
i = 20
if (i < 15):
print("i is smaller than 15")
else:
print("i is greater than 15")

Output:-
i is greater than 15

#Code with KodNest Page | 13


Topic 3 : Control Construct

6. Explain for loop in python?


The for loop is used for iterating over a sequence of elements ( list, a tuple, a dictionary, a set or
a string).

Example:-
s = [10,20,30,40,50]
for x in s:
print(x)

Output:-
10
20
30
40
50

7. Explain while loop in python?


With the while loop, we can execute a set of statements as long as a condition is true.

Example:-
i=1
while i < 6:
print(i)
i+=1

Output:-
1
2
3
4
5

8. Explain break and continue statements.


break:- break statement stops the loop in which the statement is placed.

Example:-
students = ["Paul","Erin","Connie","Moira"]
for student in range(0,len(students)):
if student == 2:
break
else:
print(students[student])

Output:-
Paul
Erin

continue:- continue statement skips a single iteration in a loop. The continue statement instructs
a loop to continue to the next iteration. Any code that follows the continue statement is not
executed. Unlike a break statement, a continue statement does not completely halt a loop.

Example:-
students = ["Paul" , "Erin" , "Connie" , "Moira"]
for student in range(0,len(students)):
if student == 2:
continue

Page | 14 #Code with KodNest


www.kodnest.com

else:
print(students[student])

Output:-
Paul
Erin
Moira

9. Write an example on for loop using range()?

Example 1:-
for i in range(0,10,3):
print(i)

Output:-
0
3
6
9

Example 2:-
for i in range(10,5,-1):
print(i)

Output:-
10
9
8
7
6

10. Write a python program to display even numbers between two given numbers using while
loop.
Program:-

a=int(input("Enter first number"))


b=int(input("Enter second number"))
num=a
while num>=a and num<=b:
if num%2==0:
print(num)
num=num+1

Output:-
Enter first number10
Enter second number20
10
12
14
16
18
20

#Code with KodNest Page | 15


Topic 3 : Control Construct

11. List the control constructs in Python.


The control constructs in python are:
1. if control construct
2. if else control construct
3. if elif else control construct
4. for loop control construct
5. while loop control construct
6. break statement
7. continue statement

Page | 16 #Code with KodNest


www.kodnest.com

TOPIC 4
METHODS
1. What are Methods in Python?
According to Object-Oriented Programming, every object consists of has-part and does-part. The
does-part of an object are the behaviours which are defined by using the methods. These methods
are defined inside a class.
The method is group of statements that are written at one place to perform a specific task. If these
group of instructions are present inside the class, they are called as methods, if they are present
outside the class, they are called as functions.

2. How many types of Methods are there in Python?


There are three types of methods in Python:
1. Instance Method
2. Class Method
3. Static Method

3. Explain returning multiple values from a method.


In Python, a method can return multiple values as shown below:-
def Calculator(a,b):
add = a+b
sub = a-b
mul = a*b
div = a/b
return add,sub,mul,div
add,sub,mul,div = Calculator(10,20)
print("The result of addition is",add)
print("The result of subtraction is",sub)
print("The result of multiplication is",mul)
print("The result of division is",div)

Output:-
The result of addition is 30
The result of subtraction is -10
The result of multiplication is 200
The result of division is 0.5

4. What is the Instance Method? Give an example.


Instance methods are used to set or get details about instances or objects. Instance methods are the
most common type of methods used in a Python class.
Every method has one default parameter, i.e., self, which points to an instance of the class. The name
of this parameter, 'self', can be changed, but it is the convention to use 'self'. Any method which is
created inside a class is an instance method.

Example:-
class KodNest:
def instance_method(self):
return "This is an instance method"

m=KodNest()
print(m.instance_method())

#Code with KodNest Page | 17


Topic 4 : Methods

Output:-
This is an instance method

5. What is the class Method? Give an example.


The class methods are used to set or get the details of the class. Hence they are known as class
methods. Class methods can't access or modify specific instance data.
Two important things about class methods:
1. The class methods are specified with the help of the @classmethod decorator.
2. The class methods accept one default parameter, i.e., cls, which points to the class. It is a
convention to name the default parameter "cls".

Example:-
class KodNest:
@classmethod
def class_method(cls):
return "This is a class method"
m=KodNest()
print(m.class_method())

Output:-
This is a class method

6. What is the Static Method? Give an example.


The static methods are defined by using the '@staticmethod' decorator (in a similar way, we used
the @classmethod decorator). Static methods can be accessed using object reference or the class
name.
Using static methods, we cannot get or set the instance state or class state. Static methods don't
accept any default parameters like instance methods and class methods. These methods cannot
access the class data.

Example:-
class KodNest:
@staticmethod
def static_method():
return "This is a static method"
m=KodNest()
print(m.static_method())

Output:-
This is a static method

7. List the different types of methods on the basis of parameters and return type in python.
There are four types of methods on the basis of parameters and return type which are as follows:-
1. Type-I Method:- The methods which do not accept input and do not return output. Means, the
method which don't have parameters and don't return any value.
2. Type-II Method:- The methods which do not accept input and returns some output. Means, the
method which don't have parameters but return some value.
3. Type-III Method:- The methods which accept input and do not return output. Means, the
method which have parameters but don't return any value.
4. Type-IV Method:- The methods which accept input and also return some output. Means, the
method which have parameters and also return some value.

8. Explain Type-I Method(No Input, No Output).


The Type-I methods are such methods which do not accept input and do not return output.
Means, the method which don't have parameters and don't return any value.

Page | 18 #Code with KodNest


www.kodnest.com

Example:-
def Calculator():
a = 100
b = 200
c = a+b
print(c)
Calculator()

Output:-
300

9. Explain Type-II Method(No Input, Output).


The Type-II methods are such methods which do not accept input and returns some output. Means,
the method which don't have parameters but return some value.

Example:-
def Calculator():
a = 100
b = 200
c = a+b
return c
res=Calculator()
print(res)

Output:-
300

10. Explain Type-III Method(Input, No Output).


The Type-III methods are such methods which accept input and do not return output. Means, the
method which have parameters but don't return any value.

Example:-
def Calculator(a,b):
c = a+b
print(c)
Calculator(100,200)

Output:-
300

11. Explain Type-IV Method(Input, Output).


The Type-IV methods are such methods which accept input and also return some output. Means, the
method which have parameters and also return some value.

Example:-
def Calculator(a,b):
c = a+b
return c
res = Calculator(100,200)
print(res)

Output:-
300

#Code with KodNest Page | 19


Topic 4 : Methods

12. What is method overloading?


Method overloading is the process of creating multiple methods with the same name but different
parameters.

Example:-
def add(num1,num2):
return num1+num2

res1=add(10,20)

def add(num1,num2,num3):
return num1+num2+num3

res2=add(10,20,30)
print(res1)
print(res2)

Output:-
30
60

13. What are the advantages of method overloading?


The advantages of method overloading is as follows:-
1. It reduces code complexities.
2. It improves the quality of the code.
3. It is also used for reusability and easy accessibility.
4. It makes code easy to understand.

14. Why Python does not support Method Overloading by default?


When there are two or more methods with the same name and are present in the same
class, the later method overrides the previous methods. As a result, during runtime, the
namespace, which has a unique name for each object present in Python, will update the
entry in the local namespace and thus avoids existing of more than one method with the
same name.

15. Give an example of method overloading.


Here we create a class with one method Hello(). The first parameter of this method is set to None.
This will give us the option to call it with or without a parameter.
An object is also created based on the class, and we will call its method using zero and one
parameter.

Example:-
def add(num1,num2):
return num1+num2
res1=add(10,20)
def add(num1,num2,num3):
return num1+num2+num3
res2=add(10,20,30)
print(res1)
print(res2)

Output:-
30
60

Page | 20 #Code with KodNest


www.kodnest.com

16. How to implement method overloading in Python?


Method overloading can be achieved by creating the methods with the same name but different
parameters.

17. What are lambda Functions?


A function without a name is called an anonymous function. Anonymous functions are defined using
the keyword lambda. Hence, they are also known as Lambda Functions.
Syntax:-
lambda arguments : expression

18. What is the difference between Lambda functions and normal functions?
The Lambda function is an anonymous function without a name created using the lambda keyword.

Example of lambda function:-


lambda num : num*num

Normal functions have a name and are created using the def keyword.

Example of normal function:-


def square(num):
return num*num

19. Explain how to use Lambda Function with List Comprehension?


The lambda function can be used with List comprehension as shown below:-

Example:-
#Program to print table
tables=[lambda x=x:x*10 for x in range(1,11)]
for table in tables:
print(table())

Output:-
10
20
30
40
50
60
70
80
90
100

20. How to use multiple statements with Python Lambda?


Lambda functions don't allow multiple statements, but two lambda functions can be created, and
other lambda functions can be called as a parameter to the first function.

Example:-
l = [[30,20,40],[90,50,70],[10,100,60,80]]
sortedlist = lambda a:(sorted(i)for i in a)
secondlargest = lambda a,f : [b[len(b)-2]for b in f(a)]

res = secondlargest(l, sortedlist)


print(res)

#Code with KodNest Page | 21


Topic 4 : Methods

Output:-
[30, 70, 80]

21. How Lambda functions can be used with filter() function?


The filter() function is useful to filter out the elements of a sequence. Lambda functions can be
used along with filter() as shown below:-

Example:-
# A lambda function with filter() function to print even numbers of a list.
list1 = [10,11,12,13,14,15,16]
list2 =list(filter(lambda num:(num%2==0),list1))
print(list2)

Output:-
[10, 12, 14, 16]

22. How can Lambda functions be used with the map() function?
The map() function accepts a function and a list as arguments. The function is called with a
lambda function, and a list and a new list are returned, which contains all the lambda modified
items returned by that function for each item.

Example:-
# A lambda function with map() to find the squares of elements in a list.
list1 =[1,2,3,4,5,6]
list2 =list(map(lambda num:num*num, list1))
print(list2)

Output:-
[1, 4, 9, 16, 25, 36]

23. How can Lambda functions be used with reduce() function?


The reduce() function reduces a sequence of elements to a single value by processing the
elements according to a function provided.

Example:-
# A lambda function with reduce()to calculate products of elements of a list.
from functools import *
list1 =[2,4,6,8]
res =reduce(lambda num1,num2 : num1*num2 ,list1)
print(res)

Output:-
384

24. Explain Nested functions?


A nested function is such a function which is defined within another function. It is also called as
inner function.

Example:-
def outer_func():
def inner_func():
print("Welcome To KodNest")
inner_func()
outer_func()

Output:-
Welcome To KodNest
Page | 22 #Code with KodNest
www.kodnest.com

25. What is the scope of a variable in a nested function?


The location where we can find a variable and access it if required is called the scope of a variable. In
a nested function, a variable scope is only inside the nested function and cannot be accessed outside
the nested function.

Example:-
def f1():
var1 = 'KodNest'
def f2():
var2 = "Technologies"
print(var1,"",var2)
f2()
print(var1)
print(var2)
f1()

Output:-
KodNest Technologies
KodNest
NameError: name 'var2' is not defined.

26. What is the filter() in python?


The filter() method filters the given sequence with the help of a function that tests each element in
the sequence to be true or not.
The syntax of filter() is as shown below:-
filter(function, sequence)

In the above syntax, function:- Represents a function name that may return either True or False.
Sequence:- It needs to be filtered. It can be sets, lists, tuples, or containers of any iterators.
The filter() returns a filtered iterator.

Example:-
#Program that filters vowels
def vowels(var):
lst=['a','e','i','o','u']
if(var in lst):
return True
else:
return False

seq = ['k', 'o', 'd', 'n', 'e','s','t']


filtered=filter(vowels, seq)
print('The vowels are :')
for i in filtered:
print(i)

Output:-
The vowels are:
o
e

#Code with KodNest Page | 23


Topic 4 : Methods

27. Explain how filter() can be used with lambda functions?


The filter() is used with Lambda functions to separate list, tuple, or sets.

Example:-
# A lambda function with filter() function to print even numbers of a list.
list1 = [10,11,12,13,14,15,16]
list2 =list(filter(lambda num:(num%2==0),list1))
print(list2)

Output:-
[10, 12, 14, 16]

28. What is Map() in Python?


The map() function acts on each element of the sequence and changes the elements. It can be
applied to a list, a tuple, a set, a dictionary, and a string and returns an iterable map object. Python
map() is a built-in function.
The syntax of map() function is shown below:-
map(function, sequence)

Example:-
#Program to find squares of elements in a list.
def square(num):
return num*num

list1=[1,2,3,4,5,6]
list2=list(map(square,list1))
print(list2)

Output:-
[1, 4, 9, 16, 25, 36]

29. What is the working of the map() function?


The map() function accepts two inputs, one as a function and the second as an iterable object.
The function passed to map() is a normal function and will iterate over all the values present in
the iterable object given. Consider a list of numbers, and the square of each of the numbers should
be found and printed. Hence to get the output, we need the function that will return the square
of the given number. It is a shown below:-

Example:-
def square(num):
return num*num

list1=[1,2,3,4,5,6]
list2=list(map(square,list1))
print(list2)

Output:-
[1,4,9,16,25,36]

30. Explain map() with Python built-in round() function.


The map() function can be used with round() built-in function as shown below:-

Program to rounds the values using built-in round() and map().


list1 =[1.2345, 2.3456, 3.4567, 4.5678, 5.6789]
list2 =map(round,list1)
print(list(list2))

Page | 24 #Code with KodNest


www.kodnest.com

Output:-
[1, 2, 3, 5, 6]

31. Explain map() with tuple.


The map() can be used as tuple as shown below:-

Program to convert lowercase elements into uppercase elements present in a tuple.


def fun(n):
return n.upper()
tup1 = ('kodnest','technologies','pvt','ltd')
list1 =map(fun, tup1)
print(list(list1))

Output:-
['KODNEST', 'TECHNOLOGIES', 'PVT', 'LTD']

32. Explain map() with Dictionary.


A dictionary is created using curly brackets {}. As the dictionary is an iterator, you can make use of it
in side map() function. map() can be used with dictionary as shown below:-
def fun(n):
return n*10
dict1 ={1,2,3,4,5}
items=map(fun, dict1)
print(list(items))

Output:-
[10,20,30,40,50]

33. Explain map() with the set.


Set is an unordered collection of items in curly brackets({ }). As a set{ } is an iterator, it can be used
in side the map()function.

Example:-
def fun(n):
return n*10
s = {1,2,3,4,5}
item = map(fun, s)
print(list(item))

Output:-
[10, 20, 30, 40, 50]

34. Explain Decorators in Python?


A decorator is a function that accepts a function as a parameter and returns a function. It takes a
function's result, modifies it, and returns it. Hence, decorators help perform some additional tasks
needed by a function.

35. What is the syntax for Decorator?


Decorators can be applied to a function using @ symbol above the function definition. It can be used
as shown below:-

@kodnest_decorator
def hello_decorator():
print("KodNest")

#Code with KodNest Page | 25


Topic 4 : Methods

36. Explain how to use Nested Decorators in Python?


Nested decorators are the multiple decorators in a single function. Nested decorators follow a
bottom-to-top approach, i.e., the reverse order.

37. How are several decorators used?


A function can be decorated multiple times. We need to define the decorator with which we want
to wrap the output string and then apply them to the function using the ‘@’. One needs to place
the decorators above the desired function.

Syntax:-
@function1
@function2
def function(name):
print(f"{name}")

Page | 26 #Code with KodNest


www.kodnest.com

TOPIC 5
STRINGS
1. What is String in Python?
A string is a sequence of characters. In Python, strings are enclosed within single quotes or double
quotes or triple single quotes or triple double-quotes.

2. How to create a string in Python?


Strings can be created by enclosing characters inside a single quote or double quotes, or triple quotes.
Single quotes and double quotes are used for single-line strings. Triple quotes are used to represent
multiline strings.

Example:-
# defining strings in Python
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)

# triple quotes string can extend multiple lines


my_string = '''Hello, welcome to
the world of
Python'''
print(my_string)

Output:-
Hello
Hello
Hello, welcome to
the world of
Python

3. How to access characters in a string?


We can access individual characters using indexing and a range of characters using string slicing.
Index starts from 0. Trying to access a character out of index range will raise an IndexError. The index
must be an integer. Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range of
items in a string by using the slicing operator :(colon).

Example:-
#Accessing string characters in Python
str= "KodNest Technologies"
print(str)
#first character
print("str[0] = ",str[0])
#last character
print("str[-1] = ", str[-1])
#slicing 2nd to 5th character
print("str[1:5] = ", str[1:5])
#slicing 6th to 2nd last character
print("str[5:-2] = ", str[5:-2])

#Code with KodNest Page | 27


Topic 5 : Strings

Output:-
KodNest Technologies
str[0] = K
str[-1] = s
str[1:5] = odNe
str[5:-2] = st Technologi

4. How to change or delete a string?


Strings in Python cannot be changed once they have been created. Strings are immutable in
Python.
We can simply reassign different strings to the same name.

Example 1:-
my_string = "KodNest Technologies"
my_string[5] = "a"

Output:-
TypeError: 'str' object does not support item assignment

Example 2:-
my_string = "KodNest Technologies"
del my_string[1]

Output:-
TypeError: 'str' object doesn't support item deletion

5. How would you convert a string into lowercase?


The lower() is used to convert string into lowercase.

Example:-
my_string = "KodNest Technologies"
print(my_string.lower())

Output:-
kodnest technologies

6. How would you convert a string into uppercase?


The upper() is used to convert string into uppercase.

Example:-
my_string = "KodNest Technologies"
print(my_string.upper())

Output:-
KODNEST TECHNOLOGIES

7. How will you capitalize the first letter of a string.


The first letter of a string can be capitalized by using the method capitalize().

Example:-
my_string = "KodNest Technologies"
print(my_string.capitalize())

Output:-
Kodnest technologies

Page | 28 #Code with KodNest


www.kodnest.com

8. Explain some methods of string.


The few methods of a string are as follows:-
1.split():– This method is used to split the string at desired points. It returns the list as a result. By
default, it splits the string in spaces. We can provide the delimiter as an argument for the method.

Example:-
a = "Welcome To KodNest"
print(a.split())

Output:-
['Welcome','To','KodNest']

Example:-
a = "Welcome To KodNest"
print(a.split("o"))

Output:-
['Welc', 'me T', ' K', 'dNest']

2. swapcase():- This method is used to swap the lowercase character into uppercase and uppercase
character into lower case.

Example:-
a = "Code with KodNest"
print(a.swapcase())

Output:-
cODE WITH kODnEST

9. Explain string intern in Python?


String interning is the process which ensures that a single character object only present in the
memory. If a character reappears then the address of same existing character will be assigned.

10. Are strings are immutable in Python?


Yes, in python strings are immutable in nature which means, once a string is created it cannot
be altered or modified. If the string is tried to be modified then the previous string object will not be
changed, rather a new string object will be created.

11. How to check the length of a String?


The length of a string can be checked by using the len() function.

Example:-
str="Welcome To KodNest"
print(len(str))
Output:-
18

12. How Strings are concatenated in Python?


The strings can be concatenated by using ‘+’ operator or join().

Example 1:-
str1="Welcome"
str2="To"
str3="KodNest"

#Code with KodNest Page | 29


Topic 5 : Strings

final_str=str1+str2+str3
print(final_str)

Output:-
WelcomeToKodNest

Example 2:-
str1="KodNest"
str2="Technologies"
final_str=''.join([str1,str2])
print(final_str)

Output:-
KodNestTechnologies

13. Write a program to compare two strings using ‘<’ operator.


str1="kodnest"
str2="KODNEST"
if str1<str2:
print("str1 is lesser than str2")
else:
print("str1 is greater than str2")

Output:-
str1 is greater than str2

14. Write a program to compare two strings using ‘>’ operator.


str1="kodnest"
str2="KODNEST"
if str1>str2:
print("str1 is greater than str2")
else:
print("str1 is lesser than str2")

Output:-
str1 is lesser than str2

15. Write a program to compare two strings using ‘>=’ operator.


str1="KODNEST"
str2="KODNEST"
if str1>=str2:
print("str1 is greater or equal than str2")
else:
print("str1 is lesser than str2")

Output:-
str1 is greater or equal than str2

16. Write a program to compare two strings using ‘<=’ operator.


str1="KODNEST"
str2="KODNEST"
if str1<=str2:
print("str1 is lesser or equal than str2")
else:
print("str1 is greater than str2")

Page | 30 #Code with KodNest


www.kodnest.com

Output:-
str1 is lesser or equal than str2

17. Write a program to compare two strings using ‘==’ operator.


str1="KODNEST"
str2="KODNEST"
if str1==str2:
print("str1 and str2 are equal.")
else:
print("str1 and str2 are not equal.")

Output:-
str1 and str2 are equal.

18. Write a program to compare two strings using ‘!=’ operator.


str1="KODNEST"
str2="TECHNOLOGIES"
if str1!=str2:
print("str1 and str2 are not equal.")
else:
print("str1 and str2 are equal.")

Output:-
str1 and str2 are not equal.

19. Explain the String formatting in Python.


In python, formatting a string can be done using the format().
Example 1:-
str1="Bangalore"
str2="Mumbai"
str3="Chennai"
final_str="{},{},{} are the cities in India.".format(str1,str2,str3)
print(final_str)

Output:-
Bangalore,Mumbai,Chennai are the cities in India.

Example 2:-
str1="Bangalore"
str2="Mumbai"
str3="Chennai"
final_str="{},{},{} are the cities in India.".format(str3,str1,str2)
print(final_str)

Output:-
Chennai,Bangalore,Mumbai are the cities in India.

Example 3:-
str1="Bangalore"
str2="Mumbai"
str3="Chennai"
final_str="{2},{1},{0} are the cities in India.".format(str1,str2,str3)
print(final_str)

Output:-
Chennai,Mumbai,Bangalore are the cities in India

#Code with KodNest Page | 31


Topic 6 : Object Orientation

TOPIC 6
OBJECT ORIENTATION
1. What Is Object-Oriented Programming in Python?
Object-oriented programming is a mechanism of looking into the world as a collection of objects.
There are 5 basic principles of object-orientation:
1. The world is collection of objects.
2. Every object is useful, no object is useless.
3. Every object is in constant interaction with other objects, no object is in isolation.
4. Every object belongs to a type. The type is known as class, type doesn't exist in reality but
object exist in reality.
5. Every object have has-part and does-part. Has-part is the state or properties of an object. Does-
part is the behaviour of an object.
There are 4 pillars of object-orientation which are as follows:-
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction

2. What are classes and objects?


A class is a model, design or plan to create the objects. It contains the data members and member
functions of an object.
An object is the instance of a class. Classes doesn't exist but object exists in reality.

3. How to define a class? Give an example.


In Python, the class is declared with the class keyword, followed by the class's name and a colon.
Any code indented below the class definition is considered part of the class's body.

Example:-
class Book:
def __init__ (self, title, quantity, author, price):
self.title = title
self.quantity = quantity
self.author = author
self.price = price
book1 = Book("Book1", 12, "Author 1", 120)
book2 = Book("Book2", 18, "Author 2", 220)
book3 = Book("Book3", 28, "Author 3",320)
print(book1.title,"",book1.quantity,"",book1.author,"",book1.price)
print(book2.title,"",book2.quantity,"",book2.author,"",book2.price)
print(book3.title,"",book3.quantity,"",book3.author,"",book3.price)

Output:-
Book1 12 Author 1 120
Book2 18 Author 2 220
Book3 28 Author 3 320

Page | 32 #Code with KodNest


www.kodnest.com

4. What is Encapsulation?
Encapsulation is the process of preventing the access of data which is present inside the class.
Encapsulation is used to provide the security to the data members of a class. Private data can only be
accessed through specific methods.

Example:-
class Employee:
def __init__(self, name, salary, project):
self.name = name
self.salary = salary
self.project = project

def show(self):
print("Name: ", self.name, 'Salary:', self.salary)

def work(self):
print(self.name, 'is working on', self.project)

emp = Employee('Raj', 8000, 'python_project')


emp.show()
emp.work()

Output:-
Name: Raj Salary: 8000
Raj is working on python_project

5. What is Inheritance?
Inheritance is the process of acquiring the properties and behaviours of parent class in child class.
The class which gives the properties and behaviours is known as parent class and the class which
acquire the properties and behaviours is called as child class.

Example:-
class Shape():
def sides(self):
print("Shape class method")

class Triangle(Shape):
def disp(self):
print("Triangle class method")

t=Triangle()
t.sides()
t.disp()

Output:-
Shape class method
Triangle class method

6. What is polymorphism?
Polymorphism is the ability of a variable, a method or an object to exhibit multiple behaviours in
different scenarios. The most common use of polymorphism in OOP occurs when a parent class
reference is used to refer to a child class object. In Python, operator overloading is an example of
polymorphism.

#Code with KodNest Page | 33


Topic 6 : Object Orientation

Example:-
class Crow():
def type(self):
print("Bird")

def color(self):
print("Black")

class Apple():
def type(self):
print("Fruit")

def color(self):
print("Red")

def func(obj):
obj.type()
obj.color()

obj_crow = Crow()
obj_apple = Apple()
func(obj_crow)
func(obj_apple)

Output:-
Bird
Black
Fruit
Red

7. What is abstraction? Give an example.


Abstraction is the process of hiding the unwanted and internal behaviours of class or methods.

Example:-
from abc import ABC, abstractmethod
class Polygon(ABC):
@abstractmethod
def sides(self):
pass

class Triangle(Polygon):
def sides(self):
print("Triangle have 3 sides")

class Pentagon(Polygon):
def sides(self):
print("Pentagon have 5 sides")

class Square(Polygon):
def sides(self):
print("Square have 4 sides")

t= Triangle()
t.sides()

Page | 34 #Code with KodNest


www.kodnest.com

p = Pentagon()
p.sides()

s = Square()
s.sides()

Output:-
Triangle have 3 sides
Pentagon have 5 sides
Square have 4 sides

8. Is main() method is required in python?


In Python programming language, the main() method is not mandatory but an option is given to the
programmer to write a main() method if required.

Example:-
class Student:
def __init__(self):
self.name="Rahul"
self.age=22
def study(self):
print("Student is studying")

def main():
s=Student()
print(s.name)
print(s.age)
s.study()

main()

Output:-
Rahul
22
Student is studying

9. What is an object and what it consists of?


The object is an instance of a class that exist in reality. It consists of two parts:-
1. Has-part:- Has-part is the state or properties of an object.
2. Does-part:- Does-part is the behaviour or functions of an object.

10. What are the examples of object-oriented programming languages?


C++, Java, Python, C# are few examples of object-oriented programming languages.

#Code with KodNest Page | 35


Topic 7 : Inheritance

TOPIC 7
INHERITANCE
1. What is Inheritance?
Inheritance is the process of acquiring the properties and behaviours of parent class in child class.
The class which gives the properties and behaviours is known as parent class and the class which
acquire the properties and behaviours is called as child class.

Example:-
class Shape():
def sides(self):
print("Shape class method")

class Triangle(Shape):
def disp(self):
print("Triangle class method")

t=Triangle()
t.sides()
t.disp()

Output:-
Shape class method
Triangle class method

2. What are the advantages of Inheritance?


The advantages of inheritance are as follows:-
1. Inheritance provides reusability of a code.
2. Inheritance reduces the development time of a project.
3. Inheritance allows to add more features to a class without modifying it.
4. It is transitive in nature, which means that if class B inherits from another class A, then all the
subclasses of B would automatically inherit from class A.
5. It increases the productivity of an organization.

3. How to inherit a base class into the derived class? Write the syntax.
A derived class can inherit the base class by just mentioning the base class in the parenthesis
after the derived class name.

Syntax:-
class derived_class(base class):
pass

4. How a class can inherit multiple classes? Write the syntax and example.
A class can inherit multiple classes by mentioning all of them inside the parenthesis.

Syntax:-
class derive-class(base class 1,base class 2,base class 3):
pass

Page | 36 #Code with KodNest


www.kodnest.com

Example:-
class Animal:
def speak(self):
print("Animal")

class Dog(Animal):
def bark(self):
print("Dog")

d=Dog()
d.bark()
d.speak()

Output:-
Dog
Animal

5. What are the types of Inheritance in Python.


In Python, there are 5 types of inheritance which are as follows:-
1) Single inheritance
2) Multiple inheritances
3) Multilevel inheritance
4) Hierarchical inheritance
5) Hybrid inheritance

6. What is single inheritance?


Single inheritance is the process in which child class or sub class is derived from only one parent
class or super class.

Syntax:-
class class1: #parent_class
pass
class class2(class1): #child_class
pass
obj_name = class2()

Example:-
class Teacher:
def teach(self):
print("Teacher is teaching.")

class PythonTeacher(Teacher):
def takeAttendance(self):
print("Python teacher is taking attendance.")

pt = PythonTeacher()
pt.teach()
pt.takeAttendance()

Output:-
Teacher is teaching.
Python teacher is taking attendance.

#Code with KodNest Page | 37


Topic 7 : Inheritance

7. What is multiple inheritance? Give syntax.


Multiple inheritance is the process in which the child class or sub class is derived or inherited
from more than one parent class or sub class.
In multiple inheritance, there will be multiple parent classes or base classes and one child class
or sub class.

Syntax:-
class parent_1:
pass
class parent 2:
pass
class child(parent_1,parent_2):
pass
obj_ref = child()

Example:-
class Human:
def disp(self):
print("I am human.")

class Teacher:
def teach(self):
print("Teacher is teaching.")

class PythonTeacher(Human,Teacher):
def takeAttendance(self):
print("Python teacher is taking attendance.")

pt = PythonTeacher()
pt.disp()
pt.teach()
pt.takeAttendance()

Output:-
I am human.
Teacher is teaching.
Python teacher is taking attendance.

8. What is multilevel inheritance?


In multilevel inheritance, we have one parent class and child class that is derived or inherited
from that parent class. We have a grand-child class that is derived from the child class.

Syntax:-
class Grand_Parent:
pass
class Parent(Grand_Parent):
pass
class Child(Parent):
pass
obj_ref = Child()

Example:-
class Human:
def disp(self):
print("I am human.")

Page | 38 #Code with KodNest


www.kodnest.com

class Teacher(Human):
def teach(self):
print("Teacher is teaching.")

class PythonTeacher(Teacher):
def takeAttendance(self):
print("Python teacher is taking attendance.")

pt = PythonTeacher()
pt.disp()
pt.teach()
pt.takeAttendance()

Output:-
I am human.
Teacher is teaching.
Python teacher is taking attendance.

9. What is Hierarchical inheritance?


Hierarchical inheritance is the process in which multiple child classes are derived or inherited from
one parent class.

Syntax:-
class Parent:
pass
class Child1(Parent):
pass
class Child2(Parent):
pass
class Child3(Parent):
pass
c1 = Child1()
c2 = Child2()
c3 = Child3()

Example:-
class Teacher:
def takeAttendance(self):
print("Teacher is taking attendance.")

class PythonTeacher(Teacher):
def teach(self):
print("Python teacher is teaching python.")

class JavaTeacher(Teacher):
def teach(self):
print("Java teacher is teaching java.")

pt = PythonTeacher()
pt.teach()
pt.takeAttendance()

jt = JavaTeacher()
jt.teach()
jt.takeAttendance()

#Code with KodNest Page | 39


Topic 7 : Inheritance

Output:-
Python teacher is teaching python.
Teacher is taking attendance.
Java teacher is teaching java.
Teacher is taking attendance.

10. What is Hybrid inheritance?


Hybrid inheritance consists of more than one type of inheritance i.e. It is the combination of
simple, multiple, multilevel and hierarchical inheritance.

Page | 40 #Code with KodNest


www.kodnest.com

TOPIC 8
STATIC
1. What are static variables?
The variables which are created outside the method and inside the class is called as Static variables.
It can be called directly by the class name or the object reference.

2. What is the static method?


The static methods are defined by using the '@staticmethod' decorator. Static methods can be
accessed using object reference or the class name.
Using static methods, we cannot get or set the instance state or class state. Static methods don't
accept any default parameters like instance methods and class methods. These methods cannot
access the class data.

Example:-
class KodNest:
@staticmethod
def static_method():
return "This is a static method"
m=KodNest()
print(m.static_method())

Output:-
This is a static method

3. How to access the static variable using the same class object? Give an example.
A static variable can be accessed directly by using the same class object with a dot operator or directly
using the class name.

Example:-
class Teacher:
name = "Rahul"
msg = "Practice python programs properly"

t = Teacher()
print(t.name,'',t.msg)
print(Teacher.name,'',Teacher.msg)

Output:-
Rahul Practice python programs properly
Rahul Practice python programs properly

4. What are the features of static method?


The features of the static method are as follows:-
1. A static method in Python is related to the class.
2. It can be called directly from the class by reference to a class name. It cannot access the class
attributes in the program.
3. It is bound only to the class. So, it cannot modify the state of the object.
4. It can only be defined inside a class but not to the objects of the class. All the objects of the class
shares only one copy of the static method.

#Code with KodNest Page | 41


Topic 8 : Static

5. What are the different ways to create static methods in Python?


Static methods can be created in 2 different ways in Python:-

1. By using staticmethod() function:-

Example:-
class KodNest:
def disp(msg):
print("Welcome To KodNest",msg)
KodNest.disp=staticmethod(KodNest.disp("code with KodNest"))

Output:-
Welcome To KodNest code with KodNest

2. By using @staticmethod decorator:-

Example:-
class KodNest:
@staticmethod
def disp(msg):
print("Welcome To KodNest",msg)
KodNest.disp("code with KodNest")

Output:-
Welcome To KodNest code with KodNest

6. How to create the static variable in python?


The static variables are created inside the class and outside the methods in python.

Example:-
class Student:
nationality="Indian"
def __init__(self,name,age):
self.name=name
self.age=age

print(Student.nationality)

s=Student("Rahul",23)
print(s.name)
print(s.age)

Output:-
Indian
Rahul
23

7. Which variables should be created as static variables?


The variables which are common for all the objects, should be created as static variable to utilize
the memory efficiently.

Example 1:- For all the citizens of India, nationality is common, so it can be created as static
variable.

Example 2:- For all the students of one university, the university name is common, so it can be
created as static variable.

Page | 42 #Code with KodNest


www.kodnest.com

8. Which methods should be created as static methods?


The methods for which object creation is not required to invoke them, should be declared as static
methods.

9. Can a static method access instance variables?


No, a static method cannot access the instance variable, it can only access the static variable.

Example:-
class Student:
nationality="Indian"
def __init__(self):
self.name="Rahul"
self.age=22

@staticmethod
def display():
print(Student.nationality)
print(self.name)
print(self.age)

s=Student()
s.display()

Output:-
Indian
Error
Error

10. Can an instance method access static variable?


Yes, an instance method can access static variable as well as instance variable.

Example:-
class Student:
nationality="Indian"
def __init__(self):
self.name="Rahul"
self.age=22

def display(self):
print(Student.nationality)
print(self.name)
print(self.age)

s=Student()
s.display()

Output:-
Indian
Rahul
22

#Code with KodNest Page | 43


Topic 9 : Constructor

TOPIC 9
CONSTRUCTOR
1. What are constructors?
Constructors are the specialized methods used for instantiating an object, to initialize the data
members of the class when an object of the class is created. In Python, the __init__ () method is
known as constructor and is always called when an object is created.

Syntax:-
class Demo:
def_init_(self):
#body of the constructor

2. What are the types of constructors?


There are two types of constructors:-
1. Default constructor
2. Parameterized constructor

3. What is the default constructor?


When no constructors are created inside the class, then the python interpreter will attach the
default constructor inside the class. The default constructor is a simple constructor which doesn't
accept any arguments, or it is a zero parameterized constructor. By default, the default
constructor has only one argument, which is a reference to the instance being constructed known
as 'self.'

Example:-
class Demo:
def disp(self):
print("Inside disp()")

d=Demo()
d.disp()

Output:-
Inside disp()

4. What is a parameterized constructor?


A constructor which accepts parameters is known as a parameterized constructor. Always the
first parameter in the constructor is a reference to the current object known as 'self' and the rest
of the parameters are provided by the programmer as per need.

Example:-
class Demo:
def __init__(self,name,age):
self.name=name
self.age=age

def disp(self):
print("Inside disp()")

Page | 44 #Code with KodNest


www.kodnest.com

d=Demo("Rahul",27)
print(d.name,"",d.age)
d.disp()

Output:-
Rahul 27
Inside disp()

5. What is the first parameter of the constructor?


The first parameter of the constructor is always ‘self’ variable, that contains the memory address of
the current object.

6. Can a constructor have multiple parameters?


Yes, constructor can have multiple parameters which can be used to initialize or store the values in
the instance variables.

Example:-
class Student:
def __init__(self,rollno,name,age):
self.rollno=rollno
self.name=name
self.age=age

s=Student(13,"Rahul",25)
print(s.rollno)
print(s.name)
print(s.age)

Output:-
13
Rahul
25

7. How to create instance variables in constructor?


The instance variables can be created in the constructor using ‘self variable’ with the variable name.

Example:-
class Student:
def __init__(self):
self.rollno=13
self.name="Rahul"
self.age=25

s=Student()
print(s.rollno)
print(s.name)
print(s.age)

Output:-
13
Rahul
25

8. What is the use of constructor?


The constructors are used to create the instance variables and initialize the objects.

#Code with KodNest Page | 45


Topic 9 : Constructor

9. When a constructor is invoked?


A constructor is invoked at the time of creating an object.

10. Can a class have multiple constructors?


A class can have multiple constructors, though it will not give compilation error but during the
object creation, the last written constructor will be invoked.

Example:-
class Student:
def __init__(self):
self.rollno=13
self.name="Rahul"
self.age=25

def __init__(self,name,age):
self.rollno=14
self.name=name
self.age=age

s=Student()
print(s.rollno)
print(s.name)
print(s.age)

Output:-
TypeError: Student.__init__() missing 2 required positional arguments: 'name' and 'age'

Page | 46 #Code with KodNest


www.kodnest.com

TOPIC 10
ACCESS SPECIFIER
1. What do you mean by access specifier?
Access specifiers or access modifiers in python programming are used to define the access of class
variables and class methods outside of class while implementing the concepts of inheritance. In
Python, there are Public, Private, and Protected access specifiers.

2. What are the types of access specifiers?


1. Public access specifier
2. Private access specifier
3. Protected access specifier

3. What is Public Access Modifier?


All the variables and methods (member functions) in Python are, by default, public. Any variable or
method in a class is suffixed with nothing is considered a public member of that class.

Example:-
class KodNest:
def disp(self):
print("Welcome To KodNest")

k=KodNest()
k.disp()

Output:-
Welcome To KodNest

4. What is Private Access Modifier?


Private members of a class (variables or methods) are those members which are accessible only
inside the class. Private members are not accessible outside of class.
Any variable in a class that is suffixed with a double underscore is considered a private member of
that class.

Example:-
class KodNest:
def __disp(self):
print("Welcome To KodNest")

k=KodNest()
k.__disp()

Output:-
Error

5. What is Protected Access Modifier?


Protected access modifier is used to define the protected variables or protected members. They are
restricted to be used only by the member functions and class members of the same class. And also, it
can be accessed or inherited by it's child class. Any variable in a class that is suffixed with a single
underscore is considered a protected member of that class.

#Code with KodNest Page | 47


Topic 10 : Access specifier

Example:-
class KodNest:
def _disp(self):
print("Welcome To KodNest")

k=KodNest()
k._disp()

Output:-
Welcome To KodNest

6. Which symbol is used to determine the access modifier in Python?


Python uses ‘_’ symbol to determine the access modifier.
For public data members or member functions, no ‘_’ symbol is used.
For protected data members or member functions, single ‘_’ symbol is used.
For private data members of member functions, double ‘_’ symbol is used.

7. Explain Data Mangling in python.


In Python for private variables the name is changed automatically. The new name will be
_className__variableName. If private variables has to be accessed outside the class, than they
can be accessed using the new name provided for them. This process is known as “Data
Mangling”. It is also called as “Name Mangling”.

Example:-
class Demo:
def __init__(self):
self.__x=10
self.__y=20

d=Demo()
print(d._Demo__x) #10
print(d._Demo__y) #20

8. Are private variables can be accessed outside the class in python?


The Private variables should be accessed in the same class only, but if private variables need to
be accessed outside the class, then it can be done using “Data Mangling” or “Name Mangling”
process.

Example:-
class Demo:
def __init__(self):
self.__x=10
self.__y=20

d=Demo()
print(d.__x) #Error
print(d.__y) #Error
print(d._Demo__x) #10
print(d._Demo__y) #20

9. Can public data members can be accessed outside the class.


Yes, public data members can be accessed outside the class and inside the class.

Page | 48 #Code with KodNest


www.kodnest.com

Example:-
class Demo:
def __init__(self):
self.x=10
self.y=20

d=Demo()
print(d.x)
print(d.y)

Output:-
10
20

10. Can protected data members can be accessed outside the class?
No protected data members cannot be accessed outside the class, they can be accessed in the child
classes.

Example:-
class Teacher:
def __init__(self):
self._name="Rahul"
self._age=30

class PythonTeacher(Teacher):
def display(self):
print(self._name) #Rahul
print(self._age) #30

print(self._name) #Error
print(self._age) #Error
pt = PythonTeacher()
pt.display()

#Code with KodNest Page | 49


Topic 11 : Polymorphism

TOPIC 11
POLYMORPHISM
1. What is polymorphism?
Polymorphism is the ability of a variable, a method or an object to exhibit multiple behaviours in
different scenarios. The most common use of polymorphism in OOP occurs when a parent class
reference is used to refer to a child class object. In Python, operator overloading is an example of
polymorphism.

Example:-
class Crow():
def type(self):
print("Bird")

def color(self):
print("Black")

class Apple():
def type(self):
print("Fruit")

def color(self):
print("Red")

def func(obj):
obj.type()
obj.color()

obj_crow = Crow()
obj_apple = Apple()
func(obj_crow)
func(obj_apple)

Output:-
Bird
Black
Fruit
Red

2. What is the purpose of using polymorphism in Python?


Polymorphism is mostly used to perform Duck Typing, Operator overloading, Method overriding,
etc.

3. What is static polymorphism?


Static polymorphism is a polymorphism that occurs at compile-time. An example of compile-time
polymorphism is method overloading.

4. What is dynamic polymorphism?


Dynamic polymorphism (dynamic binding) is also known as Runtime polymorphism. It is a
polymorphism that is resolved during runtime. An example of runtime polymorphism is method
overriding.
Page | 50 #Code with KodNest
www.kodnest.com

5. Explain Compile-time Polymorphism?


A compile-time polymorphism, also called static polymorphism, occurs during the compilation time
of the program.

6. What is method overloading?


Method overloading is the process of creating multiple methods having the same name but different
parameters. But Python doesn't support method overloading. Even though methods are overloaded,
only the recently created methods are considered by the python interpreter.

Example:-
class Calculator:
def calc(self,a,b):
print(a+b)

def calc(self,a,b,c):
print(a+b+c)

def calc(self,a,b,c,d):
print(a+b+c+d)

c=Calculator()
c.calc(10,20) # Error
c.calc(10,20,30) #Error
c.calc(10,20,30,20) #80

7. What is method overriding?


Method overriding is a process of inheriting the parent class method and changing the
implementation of the method in the child class according to the child's requirement.

Example:-
class Parent:
def display(self):
print("Inside parent class")

class Child(Parent):
def display(self):
print("Inside child class")

c=Child()
c.display()

Output:-
Inside child class

8. What is operator overloading?


Operator overloading is the process of one operator performing multiple tasks at the same time.

Example:-
class Calc:
def add(self,a,b):
print(a+b)
c=Calc()
c.add(10,20)
c.add("Kod","Nest")

#Code with KodNest Page | 51


Topic 11 : Polymorphism

Output:-
30
KodNest

9. What is Duck Typing?


Duck Typing is a concept in dynamically typed languages. It is a concept in which the type of an
object is not checked and is less important while invoking the method on an object. Instead, any
object is accepted as long as it has the presence of a given method or attribute.

10. What is duck typing language?


Duck Typing languages are dynamic languages that do not have strong typing. The idea is that
you don't need a type to invoke an existing method on an object.

11. What is the use of duck typing?


In Python, every variable or object has a type, which is implicitly assigned according to the
purpose for which the variable is created. Hence, any set of classes with a common set of methods
can be treated similarly. This is called duck typing.

Page | 52 #Code with KodNest


www.kodnest.com

TOPIC 12
MAGIC METHODS
1. What is the other name for the magic method in Python?
The magic method in Python is also called as the dunder method.

2. What is a magic method in Python?


Magic methods are special methods in Python, and these methods always begin and terminate with
a double underscore.
We can extend the operability of the operators using "Magic Methods".

Example:-
class Age:
def __init__(self,age):
self.age = age

def __ge__(self,others):
return self.age >= others.age

a = Age(40)
b = Age(20)
print(a>=b)

Output:-
True

3. How the magic methods are invoked?


Magic methods are not invoked directly, but the invocation happens internally from the class on a
specific action.

Example:-
When the object reference variable is printed, internally __str__() is invoked, which returns the
address of the reference variable of an object.

4. Which function is used to see the number of magic methods?


The dir() function shows the number of magic methods inherited by a class.

5. Where are Magic methods used?


Magic methods are used to define the overloaded behaviors of predefined operators in Python.

6. How to print all the magic methods and methods present inside int class.
dir() returns all the magic methods and methods present inside any class.
The code to print the magic method and methods present inside int class is as follows:

print(dir(int))

Output:-
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__',
'__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__',
'__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__',

#Code with KodNest Page | 53


Topic 12 : Magic methods

'__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__',
'__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__',
'__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__',
'__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__',
'__xor__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes',
'imag', 'numerator', 'real', 'to_bytes']

7. Print all the magic methods and string methods inside the str class.
dir() returns all the magic methods and methods present inside any class. Below is the code to
print the magic method present inside the str class:

print(dir(str))

Output:-
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__',
'__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs',
'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier',
'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust',
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate',
'upper', 'zfill']

8. Print all the magic methods and methods present inside float class.
dir() returns all the magic methods and methods present inside any type. Below is the code to
print the magic method present inside the float class:

print(dir(float))

Output:-
['__abs__', '__add__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__',
'__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__',
'__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__',
'__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__',
'__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__rpow__', '__rsub__',
'__rtruediv__', '__setattr__', '__setformat__', '__sizeof__', '__str__', '__sub__', '__subclasshook__',
'__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']

9. How to overload magic methods inside the class?


Magic methods can be overloaded by changing their body inside the class.

Example:-
class Person:
def __init__(self,age):
self.age = age
def __ge__(self,others):
return self.age >= others.age
def __gt__(self,others):
return self.age > others.age
def __le__(self,others):
return self.age <= others.age
def __lt__(self,others):
return self.age < others.age

Page | 54 #Code with KodNest


www.kodnest.com

def __eq__(self,others):
return self.age == others.age
def __sub__(self,others):
return self.age - others.age
def __mul__(self,others):
return self.age * others.age
def __truediv__(self,others):
return self.age / others.age

p1 = Person(40)
p2 = Person(20)
print(p1>=p2)
print(p1>p2)
print(p1<=p2)
print(p1<p2)

print(p1==p2)
print(p1-p2)
print(p1*p2)
print(p1/p2)

Output:-
True
True
False
False
False
20
800
2.0

10. List the different magic methods and its properties.

Magic Methods Description

__iadd__(self, other) This method performs the addition assignment x+=y.

__imul__(self, other) This method performs the multiplication assignment x*=y.

__isub__(self, other) This method performs the subtraction assignment x-=y.

__idiv__(self, other) This method is required to perform the division assignment x/=y.
__itruediv__(self, other) Gets called upon when true division is required.
__imod__(self, other) This method performs the modulo assignment a%=b.

__ipow__(self, other) This method performs the exponent assignment a**=b.

__ifloordiv__(self, other) This method performs the floor division assignment a//=b.

#Code with KodNest Page | 55


Topic 12 : Magic methods

Magic Methods Description

__ilshift__(self, other) This method performs the left bitwise shift assignment a <<= b.

__irshift__(self, other) This method performs the right bitwise shift assignment a >>= b.

__ixor__(self, other) This method performs the bitwise XOR assignment a^=b.
This method is required to perform the OR bitwise assignment
__ior__(self, other)
operation a|=b.
This method is required to perform the AND bitwise assignment
__iand__(self, other)
operation a &= b.
This method is required to convert an object type to int type This
__int__(self)
method is called using int().
This method is required to convert an object type to float type. It
__float__(self)
is called by float().
This method is required to convert an object type to complex type.
__complex__(self)
It is called by complex().
This method is required to convert an object type to octal type. It
__oct__(self)
is called by oct().
This method is required to convert an object type to hexadecimal.
__hex__(self)
It is called by the hex() method.
This method is present in math module. This method is called by
__trunc__(self)
trunc()
This method is called while performing slicing operation on the
__index__(self)
any object.
__pos__(self) This method performs the unary positive operation, +x.
__neg__(self) This method performs the unary negative operation, -x.
This method performs the inversion. The ~ operator is used for
__invert__(self)
inversion.
__ceil__(self) This method gets called while executing the math.ceil() function.
__floor__(self) This method gets called while executing the math.floor() function.
__round__(self, n) This method gets called while executing round().
__add__(self, other) This method gets called when the addition + operator is used.
__sub__(self, other) This method gets called when subtraction – operator is used.
__mul__(self, other) This method gets called when multiplication * operator is used.
__truediv__(self, other) This method gets called when the division/operator is used.
__floordiv__(self, other) This method gets called when using the // operator.

Page | 56 #Code with KodNest


www.kodnest.com

Magic Methods Description

__mod__(self, other) This method gets called when the mod % operator is used.

__le__(self, other) This method gets called when using the <= operator.
__lt__(self, other) This method gets called when using the < operator.
__eq__(self, other) This method gets called when using the == operator.
__ge__(self, other) This method gets called when using the >= operator.
__ne__(self, other) This method gets called when using the !=.
This method gets called when the str() method to convert
__str__(self)
something to string type.
This method gets called when the unicode() method gets
__unicode__(self)
executed.
When you are formatting a string using the format() method,
__format__(self, formatstr)
this dunder method gets called.
This dunder method returns an integer when you use the
__hash__(self)
hash() method.
Returns True or False when the bool() method gets
__nonzero__(self)
executed.
Used to return a list of attributes of a class when the dir()
__dir__(self)
method is used.
__sizeof__(self) Gets called when the getsizeof() method is called.
__getattr__(self, name) This method gets called when you are trying to access a non-
existent attribute of a class.
__setattr__(self, name) This method gets called while assigning a value to the
attribute of a class.
__delattr__(self, name) Gets called when deleting an attribute of a class.

__pow__(self, other) This method gets called when using the ** operator.

#Code with KodNest Page | 57


Topic 13 : Abstraction

TOPIC 13
ABSTRACTION
1. What is Abstraction in Python?
Abstraction is the process of hiding the unwanted and internal behaviours of class or methods.

Example:-
from abc import ABC, abstractmethod

class Polygon(ABC):
@abstractmethod
def sides(self):
pass

class Triangle(Polygon):
def sides(self):
print("Triangle have 3 sides")

class Pentagon(Polygon):
def sides(self):
print("Pentagon have 5 sides")

class Square(Polygon):
def sides(self):
print("Square have 4 sides")

t= Triangle()
t.sides()

p = Pentagon()
p.sides()

s = Square()
s.sides()

Output:-
Triangle have 3 sides
Pentagon have 5 sides
Square have 4 sides

2. What is an abstract class?


An abstract class is a class that consists of one or more abstract methods. It can also contain
concrete methods.

3. Why do we need abstraction in Python?


In Python, if a programmer needs to hide all their relevant data/processes of an application to
reduce complexity and increase efficiency, then abstraction can be used.

4. Can an abstract class be instantiated?


Abstract classes can't be instantiated, or objects can't be created for the abstract class.

Page | 58 #Code with KodNest


www.kodnest.com

5. Can abstract methods have a body?


No, abstract method does not contain the body or implementation.

6. What is an abstract method?


An abstract method doesn't have a method body or implementation. Its body should be provided in
the sub-classes. To declare the abstract method, a decorator @abstract method is used above them.

7. An abstract class must have only abstract methods. True or false?


False. An abstract class can also have concrete methods.

8. What is @abstract method decorator?


@abstract method is a decorator that is used to declare the abstract methods.

9. Is it mandatory for an abstract class to have at least one abstract method?


Not necessarily. An abstract class may or may not have an abstract method.

10. Can we instantiate a class that does not have a single abstract method but is declared abstract?
No, we can't instantiate a class once it is declared abstract even though it does not have abstract
methods.

#Code with KodNest Page | 59


Topic 14 : Operator Overloading

TOPIC 14
OPERATOR OVERLOADING
1. What is operator overloading?
The operator over loading provides additional meaning to an operator beyond their pre defined
operational meaning. Such as, we can use the "+" operator for adding two integers, joining two
strings or merging two lists.

Example:-
x=10
y=20
print(x+y)
z=10.4
print(x+z)
s1='kodnest'
s2='technologies'
print(s1+s2)
l1=[10,20,30]
l2=[20,30,40]
print(l1+l2)

Output:-
30
20.4
kodnesttechnologies
[10, 20, 30, 20, 30, 40]

2. Why do we need operator overloading?


The operator overloading provides additional meaning to an operator beyond their pre-defined
operational meaning.

3. The "+" operator is overloaded by which class?


The "+" operator is overloaded by the "int" class and "str" class.

4. Can the user create a new operator?


The user can overload all the existing operators, but they cannot create any new operators.

5. Which function is automatically invoked when the user uses the "+" operator?
When the user uses the "+" operator, the magic function __add__() will automatically invoke in
the command where the "+" operator will be defined.

6. Which function is automatically invoked when the user uses the "*"operator?
When the user uses the "*" operator, the magic function __mul__() will automatically invoke the
command where the "*" operator will be defined.

7. Which function is automatically invoked when the user uses the "%" operator?
When the user uses the "%" operator, the magic function __mod__() will automatically invoke in
the command where the "%" operator will be defined.

Page | 60 #Code with KodNest


www.kodnest.com

8. Which function is automatically invoked when the user uses the "-" operator?
When the user uses the "-" operator, the magic function __sub__() will automatically invoke in the
command where the "-"operator will be defined.

9. Which function is automatically invoked when the user uses the "/" operator?
When the user uses the "/" operator, the magic function __div__() will automatically invoke in the
command where the"/" operator will be defined.

10. Which function is automatically invoked when the user uses the "<" operator?
When the user uses the "<" operator, the magic function __lt__() will automatically invoke in the
command where the "<" operator will be defined.

11. Which function is automatically invoked when the user uses the ">" operator?
When the user uses the ">" operator, the magic function __gt__() will automatically invoke in the
command where the ">" operator will be defined.

12. Which function is automatically invoked when the user uses the "<=" operator?
When the user uses the "<=" operator, the magic function __le__() will automatically invoke in the
command where the "<=" operator will be defined.

13. Which function is automatically invoked when the user uses the ">=" operator?
When the user uses the ">=" operator, the magic function __ge__() will automatically invoke in the
command where the ">=" operator will be defined.

14. Which function is automatically invoked when the user uses the "==" operator?
When the user uses the "==" operator, the magic function __eq__() will automatically invoke in the
command where the "=="operator will be defined.

15. Which function is automatically invoked when the user uses the "!=" operator?
When the user uses the "!="operator, the magic function __ne__() will automatically invoke in the
command where the "!="operator will be defined.

#Code with KodNest Page | 61


Topic 15: Exception Handling

TOPIC 15
EXCEPTION HANDLING
1. What is Exception Handling?
Exception handling is the mechanism to handle the runtime exceptions so that program will not
terminate abruptly.

2. What is the difference between syntax errors and exceptions?


Syntax Error:- They are also known as compile-time errors. These errors are caused by the wrong
syntax in the code, due to which a program fails to compile.

Example:-
x="KodNest
print(x)

Output:-
unterminated string literal

Exceptions:- An exception is a runtime error that occurs during the execution of a program and
can abruptly terminate the program.

Example:-
a=10
b=0
c=a/b
print(c)

Output:-
Zero Division Error: division by zero

3. What is the try and except blocks in Python?


The try and except blocks are used to catch and handle exceptions. The Try block contains the
statements which might generate the exceptions. The except block handles the exceptions that
are raised in the try block.

Example:-
Accessing the array element whose index is out of bound and handling the corresponding
Exception.
a = [100, 200, 300]
try:
print (a[3])
except:
print ("Exception handled")

Output:-
Exception handled

In the above example, the statement that can cause the error is placed inside the try statement.
The statement that must be executed after handling the exception is kept inside the except block.

Page | 62 #Code with KodNest


www.kodnest.com

4. Why multiple except blocks are used in Python?


A try statement can have multiple except blocks to catch and handle the specific exceptions.
The general syntax for adding specific exceptions is:-

try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)

5. Explain try, except, else and finally working in exception handling?


1. Try => The try block contains the statements which might generate the exceptions.
2. Except => The except block catches and handles the exception.
3. Else => The statements inside the else block are executed if no exception is raised.
4. Finally => Irrespective of whether exceptions are occurring, the statements inside the final block
are always executed.

Example:-
try:
#statements which can generate the exception
except Exception1:
#statements which should be executed if Exception1 occurs
except Exception2:
#statements which should be executed if Exception2 occurs
else:
#statements which will get executed if an Exception will not occur
finally:
#statements that will always execute

6. Explain Finally block in Python?


Finally block is used to write such statements, which is always executed after the try and except
blocks. The finally block always executes after the normal termination of the try block or after the try
block terminates due to some exception.

Example:-
try:
a=int(input("Enter the first number"))
b=int(input("Enter the second number"))
k = a/b # raises divide by zero exception.
print(k)
except Exception:
print("Can't divide by zero")
finally:
print("It is always executed")

Output Scenario-1 (When an exception is not generated):-


Enter the first number10
Enter the second number5
2.0
It is always executed

Output Scenario-2 (When an exception is generated):-


Enter the first number10
Enter the second number0
Can't divide by zero
It is always executed
#Code with KodNest Page | 63
Topic 15: Exception Handling

7. List the common built-in Exceptions.


Few built-in Exceptions are as follows:-
1. Arithmetic Error => It is the parent class for arithmetic errors like Overflow Error, Zero
Division Error, etc.
2. Index Error => When the wrong index of a list is retrieved.
3. Assertion Error => It occurs when the assert statement fails.
4. Attribute Error => It occurs when an attribute reference or assignment is failed.
5. Import Error => It occurs when an imported module is not found.
6. Type Error => It occurs when a function and operation are applied in an incorrect type.
7. Key Error => It occurs when the key of the dictionary is not found.
8. Memory Error => It occurs when a program runs out of memory.
9. Name Error => It occurs when the variable is not defined.

8. What are the Built-in Exceptions?


In Python language, several internal exception classes are available to handle the exceptions,
which are known as built-in Exception.

Example:- Exception, Arithmetic Error, Over flow Error, Zero Division Error, Floating Point Error,
Assertion Error, Attribute Error, EOF Error, Generate Exit, IO Error, Import Error, Name Error,
Runtime Error, Index Error, Type Error, Value Error, Syntax Error, etc.

9. What is a user-defined Exception?


In Python, the programmer can create exceptions per the requirement or need. These exceptions
are known as a user-defined exceptions.
If a number is divided by zero, Zero Division Error is raised. If a data type is incorrect, Type Error
is raised, but in some scenarios where built-in exceptions are helpful, the programmer has to
create the user-defined exceptions.

10. Create a user-defined Exception and demonstrate using an example.


Example:-
class InvalidAgeException(Exception):
def __init__(self,msg):
self.msg=msg

class DrivingLicense:
def __init__(self,age):
self.age=age

def validate(self):
if self.age<18 or self.age>65:
raise InvalidAgeException
else:
print("You have successfully applied for Driving License")

age=int(input("Enter your age"))


dl=DrivingLicense(age)
try:
dl.validate()
except Exception:
print("You are not eligible for Driving License")

Output:-
Enter your age 10
You are not eligible for Driving License

Page | 64 #Code with KodNest


www.kodnest.com

TOPIC 16
FILE HANDLING
1. What is the difference between r+ and w+ mode?
If file does not exist then r+ mode will return error and w+ mode will create a new file.

2. What is the difference between write and append mode?


Write mode overwrites the existing data and append mode add the new data at the end of the file.

3. What is the similarity in between a+ and w+?


The similarity between a+ and w+ is that in both the modes, we can do read and write operations.

4. What is the difference between a+ and w+?


The difference between a+ and w+ is that w+ mode file will be truncated while in a+ mode, file’s
existing data will not be deleted and new data will be added at the end of the file.

5. What is the difference between read() and read(n) functions?


The difference between read() and read(n) is that the read() will read entire data from the file and
read(n) will read first n characters/bytes from the file.

6. What is the difference between readline() and readlines() ?


The difference between readline() and readlines(n) is that the readline() function will read one line
from the file and readlines() function will read all the lines from the files.

7. Name two functions which are used to write data into file.
The two functions to write data into file are write() and writelines().

8. Write a program to read entire content from the file named “kodnest.txt”
f = open(“kodnest.txt, “r”)
d = f.read()
print(d)

9. Write the statement to close the file “kodnest.txt” which is associated with file object named
“kodnest”.
kodnest.close()

10. What is the use of 'w' file mode?


The 'w' file mode is used to write the data into file. If some data is already present in file, then it will
be removed and new data will be stored.

11. What is the use of 'r' file mode?


The 'r' file mode is used to read the data from file.

12. What is the use of 'a' file mode?


The 'a' file mode is used to append the data into file at the end.

#Code with KodNest Page | 65


Topic 17: Django

TOPIC 17
DJANGO
1. What is Django?
Django is a Python framework that makes web application development easier. It's a free and
open-source framework. Django framework makes developers focus on new application
components instead of already developed ones. It is most preferred because it is fast, flexible,
suitable for any web app development, secure, scalable, and portable.

2. Django framework is used for backend or frontend?


Django is suitable for both the backend and frontend. It's a collection of Python libraries that
allow you to develop useful web apps for both the backend and frontend.

3. What is the difference between the Python language and the Django framework?
Python is a programming language used for various applications: machine learning, artificial
intelligence, desktop apps, etc. Django is a Python web framework for full-stack app and server
development.

4. What is the architecture used by Django?


Django framework uses a Model-Template-View(MTV) architecture. This architecture consists of
three different parts:
1. Model: The data should be presented from a database.
2. View: It's a user interface. It handles the request from the user and returns the relevant
template.
3. Template: It is a file contains to logic to display the data.

5. What are the advantages of using the Django framework?


Django has many advantages, which are as follows:-
1. Django follows MTV architecture (Model-Template-View).
2. It is fast and flexible.
3. It is free and open-source.
4. It is portable.
5. It is secured and scalable.
6. It has plenty of inbuilt libraries.
7. It provides support for ORM.

6. What is the use of the middle-wares in Django?


Middleware is something that executes between the request and response. In simple words, you
can say it acts as a bridge between the request and response. Similarly, In Django, when a request
is made, it moves through middleware to views, and data is passed through middleware as a
response.

7. Explain Django URL.


URLs are an essential part of a web application, and using Django, and the URL can be designed
according to the programmer's need. These URLs can be static as well as dynamic.

Page | 66 #Code with KodNest


www.kodnest.com

8. Explain the structure of a Django project.


A Django project contains the following files:
1.manage.py => manage.py is the command line utility of your Django project and controls the Django
project on the server.
2.settings.py => settings.py file includes information on all the apps installed in the project.
3.init.py => The init.py file is an empty file that makes the python interpreter understand that the
directory consisting of settings.py is a module/package.
4.urls.py => The urls.py file acts as a map for the whole web project.
5.wsgi.py=>The wsgi.py file is for the server format WSGI.

#Code with KodNest Page | 67


Topic 18 : Programs On Python

TOPIC 18
PROGRAMS ON PYTHON
1. Write a python program to swap two numbers.
Program:-

x=int(input("Enter the first number"))


y=int(input("Enter the second number"))
print("The numbers before swapping are:",x,y)
temp = x
x=y
y = temp
print("The numbers after swapping are:",x,y)

Output:-
Enter the first number10
Enter the second number20
The numbers before swapping are: 10 20
The numbers after swapping are: 20 10

2. Write a python program to swap two numbers without using a third variable.
Program:-

x=int(input("Enter the first number"))


y=int(input("Enter the second number"))
print("The numbers before swapping are:",x,y)
x=x+y;
y=x-y;
x=x-y;
print("The numbers after swapping are:",x,y)

Output:-
Enter the first number10
Enter the second number20
The numbers before swapping are: 10 20
The numbers after swapping are: 20 10

3. Write a python program to check whether a given number is positive, negative or zero.
Program:-

def fun(num):
if num>0:
print(num,"is a positive number.")
elif num<0:
print(num,"is a negative number.")
else:
print(num,"is zero.")
num = int(input("Enter a number:"))
fun(num)

Page | 68 #Code with KodNest


www.kodnest.com

Output:-
Enter a number:10
10 is a positive number.

4. Write a python program to check whether a given number is even or odd.


Program:-

def fun(num):
if num%2 == 0:
print(num,"is even number")
else:
print(num,"is odd number")
num = int(input("Enter a number: "))
fun(num)

Output:-
Enter a number: 4
4 is even number

5. Write a python program to check whether a given number is a prime number.


Program:-

def fun(num):
count=0
for i in range(1,num+1):
if num%i==0:
count=count+1
if count==2:
print(num,"is a prime number.")
else:
print(num,"is not a prime number.")

num = int(input("Enter a number: "))


fun(num)

Output:-
Enter a number: 11
11 is a prime number.

6. Write a python program to print all possible prime numbers from 1 to n.


Program:-

def fun(num):
count=0
for i in range(1,num+1):
count=0
for j in range(1,i+1):
if i%j==0:
count=count+1
if count==2:
print(i)
num = int(input("Enter a number: "))
fun(num)

#Code with KodNest Page | 69


Topic 18 : Programs On Python

Output:-
Enter a number: 20
2
3
5
7
11
13
17
19

7. Write a python program to print all the possible prime numbers in a range.
Program:-

lower_value = int(input("Please, Enter the Lowest Range Value: "))


upper_value = int(input("Please, Enter the Upper Range Value: "))
print ("The Prime Numbers in the range are: ")
for number in range (lower_value, upper_value + 1):
if number > 1:
for i in range (2, number):
if(number % i) == 0:
break
else:
print(number)

Output:-
Please, Enter the Lowest Range Value: 10
Please, Enter the Upper Range Value: 25
The Prime Numbers in the range are:
11
13
17
19
23

8. Write a python program to print the factorial of a given number.


Program:-

num = int(input("Enter a number: "))


fact = 1
if num < 0:
print("Kindly enter the positive number")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
fact = fact*i
print("The factorial of",num,"is",fact)

Output:-
Enter a number: 5
The factorial of 5 is 120

Page | 70 #Code with KodNest


www.kodnest.com

9. Write a python program to print the multiplication table of a given number.


Program:-

num = int(input ("Enter the number to print the multiplication table: "))
print ("The Multiplication Table of: ", num)
for i in range(1, 11):
print (num, 'x', i, '=', num*i)

Output:-
Enter the number to print the multiplication table: 4
The Multiplication Table of: 4
4x1=4
4x2=8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40

10. Write a python program to print the Fibonacci series till n.


Program:-

n = int(input ("Enter value of n:"))


n1 = 0
n2 = 1
count = 0
if n<=0:
print ("Please enter a positive integer.")
elif n==1:
print ("The Fibonacci sequence of the numbers up to", n, ": ")
print(n1)
else:
print ("The fibonacci sequence of the numbers is:")
while count<n:
print(n1)
n3 = n1 + n2
n1 = n2
n2 = n3
count = count+1

Output:-
Enter value of n:8
The fibonacci sequence of the numbers is:
0
1
1
2
3
5
8
13

#Code with KodNest Page | 71


Topic 18 : Programs On Python

11. Write a python program to find the L.C.M. of two numbers.


Program:-

def lcm(num1, num2):


if num1 > num2:
greater = num1
else:
greater = num2
while(True):
if((greater % num1 == 0) and (greater % num2 == 0)):
lcm = greater
break
greater = greater+1
return lcm
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))

Output:-
Enter first number: 5
Enter second number: 8
The L.C.M. of 5 and 8 is 40

12. Write a python program to find the H.C.F. of two numbers.


Program:-

def hcf(num1, num2):


if num1>num2:
smaller = num2
else:
smaller = num1
for i in range(1,smaller + 1):
if((num1 % i == 0) and (num2 % i == 0)):
hcf = i
return hcf
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The H.C.F. of", num1,"and", num2,"is", hcf(num1, num2))

Output:-
Enter first number: 4
Enter second number: 8
The H.C.F. of 4 and 8 is 4

13. Write a python program to find the sum of all elements present in an array.
Program:-

def fun(arr):
sum=0
for i in arr:
sum = sum + i
return(sum)
arr=[]
arr = [10,20,30,40,50]
n = len(arr)

Page | 72 #Code with KodNest


www.kodnest.com

res = fun(arr)
print ('The sum of the elements present in the array is', res)

Output:-
The sum of the elements present in the array is 150

14. Write a python program to find the largest element in an array.


Program:-

def fun(arr,length):
max = arr[0]
for i in range(1, length):
if arr[i] > max:
max = arr[i]
return max
arr = [45, 55, 75, 85, 35]
length = len(arr)
res = fun(arr,length)
print("The largest number present in given array is",res)

Output:-
The largest number present in given array is 85

15. Write a python program to copy all elements of one array into another array.
Program:-

arr1 = [10, 20, 30, 40, 50];


arr2 = [None] * len(arr1);
for i in range(0, len(arr1)):
arr2[i] = arr1[i];
print("Elements of original array: ");
for i in range(0, len(arr1)):
print(arr1[i]),
print();
print("Elements of new array: ");
for i in range(0, len(arr2)):
print(arr2[i]),

Output:-
Elements of original array:
10
20
30
40
50
Elements of new array:
10
20
30
40
50

#Code with KodNest Page | 73


Topic 18 : Programs On Python

16. Write a python program to find the duplicate element present in an array.
Program:-

arr = [10,20,30,40,20,40,50,30,60,70,80];
print("Duplicate elements in given array: ");
for i in range(0, len(arr)):
for j in range(i+1, len(arr)):
if(arr[i] == arr[j]):
print(arr[j])

Output:-
Duplicate elements in given array:
20
30
40

17. Write a python program to elements present in an array in reverse order.


Program:-

arr = [10, 20, 30, 40, 50]


print("Original array: ")
for i in range(0, len(arr)):
print(arr[i],end=' ')
print()
print("Array in reverse order: ")
for i in range(len(arr)-1, -1, -1):
print(arr[i],end=' ')

Output:-
Original array:
10 20 30 40 50
Array in reverse order:
50 40 30 20 10

18. Write a python program to sort an array in an ascending order.


Program:-

arr = [100,50,150,25,125,75,175]
temp = 0
print("Elements of original array: ")
for i in range(0, len(arr)):
print(arr[i], end=" ");

for i in range(0, len(arr)):


for j in range(i+1, len(arr)):
if(arr[i] > arr[j]):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
print()
print("Elements of array sorted in ascending order: ")
for i in range(0, len(arr)):
print(arr[i], end=" ")

Page | 74 #Code with KodNest


www.kodnest.com

Output:-
Elements of original array:
100 50 150 25 125 75 175
Elements of array sorted in ascending order:
25 50 75 100 125 150 175

19. Write a python program to reverse a string.


Program:-

def fun(str):
str1 = ""
for i in str:
str1 = i + str1
return str1

str = input("Enter a string :")


revstr=fun(str)
print("The original string is: ",str)
print("The reverse string is",revstr)

Output:-
Enter a string :Welcome To KodNest
The original string is: Welcome To KodNest
The reverse string is tseNdoK oT emocleW

20. Write a python program to check whether a given string is palindrome or not.
Program:-

def fun(str):
for i in range(0, int(len(str)/2)):
if str[i] != str[len(str)-i-1]:
return False
return True
str = input("Enter a string :")
res = fun(str)
if res==True:
print(str,"is palindrome.")
else:
print(str,"is not a palindrome")

Output:-
Enter a string :MADAM
MADAM is palindrome.

21. Write a python program to convert a list into a string.


Program:-

def fun(list1):
str = ''
for i in list1:
str += i
return str
list1 = ["Welcome","To", "KodNest","Technologies"]
s=fun(list1)

print(s)
print(type(s))
#Code with KodNest Page | 75
Topic 18 : Programs On Python

Output:-
WelcomeToKodNestTechnologies
<class 'str'>

22. Write a python program to remove the punctuations in a given string.


Program:-

punctuation_var = '''''!()-[]{};:'"\,<>./?@#$%^&*_~'''
str = input("Enter a string: ")
no_punctuation_str = ""
for i in str:
if i not in punctuation_var:
no_punctuation_str = no_punctuation_str + i
print(no_punctuation_str)

Output:-
Enter a string: {Welcome} (To) @Kod<Nest>
Welcome To KodNest

23. Write a python program to remove a specific index character in a string.


Program:-

str1 = input("Enter a string:")


index=int(input("Enter the index of a character to remove"))
str2 = ""
for i in range(len(str1)):
if i!= index:
str2 = str2 + str1[i]
print ("The original string is : " + str1)
print ("The string after removal of",index,"character : " + str2)

Output:-
Enter a string:Welcome To KodNest
Enter the index of a character to remove5
The original string is : Welcome To KodNest
The string after removal of 5 character : Welcoe To KodNest

24. Write a python program to find the sum of all the values in a given dictionary.
Program:-

def fun(dict):
list = []
for i in dict:
list.append(dict[i])
final = sum(list)
return final
dict = {'x': 10, 'y': 20, 'z': 30}
res=fun(dict)
print("The sum of all values in the dictionary",dict,"is: ", res)

Output:-
The sum of all values in the dictionary {'x': 10, 'y': 20, 'z': 30} is: 60

Page | 76 #Code with KodNest


www.kodnest.com

25. Write a python program to print the unique values present in a dictionary.
Program:-

dict = {'KodNest':[10,20,30,40],'is':[10,50,30,60],'awesome':[20,70,80,90]}
print("The original dictionary is : " + str(dict))
res = list(sorted({ele for val in dict.values() for ele in val}))
print("The unique values list is : " + str(res))

Output:-
The original dictionary is : {'KodNest': [10, 20, 30, 40], 'is': [10, 50, 30, 60], 'awesome': [20, 70, 80,
90]}
The unique values list is : [10, 20, 30, 40, 50, 60, 70, 80, 90]

26. Write a python program to check whether a string can become palindrome by rearranging it
or not.
Program:-

alphabets = 256
def func(str) :
count=[0]*(alphabets)
for i in range( 0, len(str)) :
count[ord(str[i])] = count[ord(str[i])] + 1
num = 0
for i in range(0, alphabets ) :
if (count[i] & 1) :
num = num + 1
if (num > 1) :
return False
return True

str=input("Enter a string")
res=func(str)
if(res==True):
print("Yes")
else :
print("No")

Output:-
Enter a string DMAMA
Yes

27. Write a python program to print the first character and last character of a given string.
Program:-

str=input("Enter a string")
print("Orignal String: ",str)
print("First character of String is:",str[0])
print("Last character of String is:",str[-1])

Output:-
Enter a stringKodNest
Orignal String: KodNest
First character of String is: K
Last character of String is: t

#Code with KodNest Page | 77


Topic 18 : Programs On Python

28. Write a python program to sort the words in a given string.


Program:-

str = input("Enter a string: ")


words = str.split()
words.sort()
for word in words:
print(word)

Output:-
Enter a string: Welcome To KodNest
KodNest
To
Welcome

29. Write a python program to find the factorial of a given number using recursion.
Program:-

def fact(n):
if n==1:
return n
else:
return n*fact(n-1)

num = int(input("Enter a number: "))

if num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",fact(num))

Output:-
Enter a number: 5
The factorial of 5 is 120

30. Write a python program to find the sum of two matrices.


Program:-

m1 = [[2,3,4],[5,6,7]]

m2 = [[1,2,3],[4,5,6]]

res = [[0,0,0],[0,0,0]]

for i in range(len(m1)):
for j in range(len(m1[0])):
res[i][j] = m1[i][j] + m2[i][j]

for x in res:
print(x)

Output:-
[3, 5, 7]
[9, 11, 13]

Page | 78 #Code with KodNest


www.kodnest.com

31. Write a python program to check whether the given strings are anagram or not.
Program:-

str1 = input("Enter first string")


str2 = input("Enter second string")
str1 = str1.lower()
str2 = str2.lower()

if(len(str1) == len(str2)):
str1_sorted = sorted(str1)
str2_sorted = sorted(str2)
if(str1_sorted == str2_sorted):
print(str1 + " and " + str2 + " are anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")

Output:-
Enter first string LISTEN
Enter second string SILENT
listen and silent are anagram.

32. Write a python program to print all possible permutations of a given string.
Program:-

def func(str, i=0):


if i == len(str):
print("".join(str))
for j in range(i, len(str)):
chars = [c for c in str]
chars[i], chars[j] = chars[j], chars[i]
func(chars, i + 1)
str=input("Enter a string")
print(func(str))

Output:-
Enter a string XYZ
XYZ
XZY
YXZ
YZX
ZYX
ZXY

33. Write a python program to check whether the given string is pangram or not.
Program:-

def func(str):
alphabets = "abcdefghijklmnopqrstuvwxyz"
for i in alphabets:
if i not in str:
return False
return True

str = input("Enter a string")


str=str.lower()
#Code with KodNest Page | 79
Topic 18 : Programs On Python

res=func(str)
if(res==True):
print("The string is pangram.")
else:
print("The string is not a pangram.")

Output:-
Enter a string The quick Brown Fox Jumps Over The Lazy dog
The string is pangram.

34. Write a python program to find the runner up score from the score sheet.
Note: You are given n scores, store them in a list and find the score of runner-up.

Input Format:
The first line contains n. The second line contains an array arr[] of n integers each
separated by a space.

Output Format:
Print the runner-up score.

Sample Input:
Enter the number of scores:
6
Enter the scores: 2 3 4 5 6

Sample Output:
The runner-up score is: 5

Program:-

print("Enter the number of scores:")


n = int(input())
arr = map(int, input("Enter the scores: ").split())
print("The runner-up score is:",sorted(list(set(arr)))[-2])

Output:-
Enter the number of scores:
6
Enter the scores: 2 3 4 5 6
The runner-up score is: 5

35. Write a python program to print the average of the marks for the student up to 2 places
after the decimal.
Note: You are given a dictionary containing the {name : marks} for students. You have to
find the average marks for a student name provided.

Input Format:
The first line contains the integer n, the number of students’s records.
The next n lines contain the names and marks obtained by a student, each value
separated by a space.
The final line contains the name of a student for which average should be printed.

Output Format:
Print the average of the marks obtained by the particular student up to 2 decimal places.

Page | 80 #Code with KodNest


www.kodnest.com

Sample Input:
Enter the number of students 3
Enter the name and marks for students Rahul 40 50 60
Enter the name and marks for students Mohan 50 60 70
Enter the name and marks for students Simran 60 70 80
Enter the name of student to display the average Mohan

Sample Output:
60.00

Program:-

n = int(input("Enter the number of students"))


students = {}
for _ in range(n):
name, *line = input("Enter the name and marks for students").split()
scores = list(map(float, line))
students[name] = scores

student_name = input("Enter the name of student to display the average")


output = list(students[student_name])
per = sum(output)/len(output);

print("%.2f" % per);

Output:-
Enter the number of students 3
Enter the name and marks for students Rahul 40 50 60
Enter the name and marks for students Mohan 50 60 70
Enter the name and marks for students Simran 60 70 80
Enter the name of student to display the average Mohan
60.00

#Code with KodNest Page | 81

You might also like