Python Book
Python Book
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.
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.
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.
C Python
C has for loop, while loop, do-while loop. Python has for loop and while loop.
Java Python
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.
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.
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.
Example:-
a=2
print(a, "is of type", type(a))
Output:-
2 is of type int
Example:-
b = 1.5
print(b, "is of type", type(b))
Output:-
1.5 is of type float
Example:-
x = True
print(x)
print(type(x))
Output:-
True
bool
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!!!
Example:-
x=4+5j
print(x)
print(type(x))
Output:-
4+5j
complex
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'>
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'>
Example:-
t2 = ("Apple", "Banana", "Orange")
print(t2)
print(type(t2))
Output:-
('Apple', 'Banana', 'Orange')
<class 'tuple'>
Example:-
s = {"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}
print(s)
print(type(s))
Output:-
{'thursday', 'friday', 'monday', 'sunday', 'wednesday', 'saturday', 'tuesday'}
<class 'set'>
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'
Example:-
a = [10,20,30,40,50]
a.append(99)
print(a)
Output:-
[10, 20, 30, 40, 50, 99]
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]
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]
Example:-
a=[10,20,30,40,50]
print(a)
a.reverse()
print(a)
Output:-
[10, 20, 30, 40, 50]
[50, 40, 30, 20, 10]
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'}
{}
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'}
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'])
Example:-
tup = (10,20,30,10,40,50,10)
print(tup.count(10))
Output:-
3
Example:-
tup = (10,20,30,10,40,50,10)
print(tup.index(10))
Output:-
0
Example:-
tup = (100,50,150,25,125,75,175)
print(sorted(tup))
Output:-
[25, 50, 75, 100, 125, 150, 175]
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
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.
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.
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
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
Example:-
s = [10,20,30,40,50]
for x in s:
print(x)
Output:-
10
20
30
40
50
Example:-
i=1
while i < 6:
print(i)
i+=1
Output:-
1
2
3
4
5
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
else:
print(students[student])
Output:-
Paul
Erin
Moira
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:-
Output:-
Enter first number10
Enter second number20
10
12
14
16
18
20
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.
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
Example:-
class KodNest:
def instance_method(self):
return "This is an instance method"
m=KodNest()
print(m.instance_method())
Output:-
This is an instance method
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
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.
Example:-
def Calculator():
a = 100
b = 200
c = a+b
print(c)
Calculator()
Output:-
300
Example:-
def Calculator():
a = 100
b = 200
c = a+b
return c
res=Calculator()
print(res)
Output:-
300
Example:-
def Calculator(a,b):
c = a+b
print(c)
Calculator(100,200)
Output:-
300
Example:-
def Calculator(a,b):
c = a+b
return c
res = Calculator(100,200)
print(res)
Output:-
300
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
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
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.
Normal functions have a name and are created using the def keyword.
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
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)]
Output:-
[30, 70, 80]
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]
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
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
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.
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
Output:-
The vowels are:
o
e
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]
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]
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]
Output:-
[1, 2, 3, 5, 6]
Output:-
['KODNEST', 'TECHNOLOGIES', 'PVT', 'LTD']
Output:-
[10,20,30,40,50]
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]
@kodnest_decorator
def hello_decorator():
print("KodNest")
Syntax:-
@function1
@function2
def function(name):
print(f"{name}")
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.
Example:-
# defining strings in Python
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
Output:-
Hello
Hello
Hello, welcome to
the world of
Python
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])
Output:-
KodNest Technologies
str[0] = K
str[-1] = s
str[1:5] = odNe
str[5:-2] = st Technologi
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
Example:-
my_string = "KodNest Technologies"
print(my_string.lower())
Output:-
kodnest technologies
Example:-
my_string = "KodNest Technologies"
print(my_string.upper())
Output:-
KODNEST TECHNOLOGIES
Example:-
my_string = "KodNest Technologies"
print(my_string.capitalize())
Output:-
Kodnest technologies
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
Example:-
str="Welcome To KodNest"
print(len(str))
Output:-
18
Example 1:-
str1="Welcome"
str2="To"
str3="KodNest"
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
Output:-
str1 is greater than str2
Output:-
str1 is lesser than str2
Output:-
str1 is greater or equal than str2
Output:-
str1 is lesser or equal than str2
Output:-
str1 and str2 are equal.
Output:-
str1 and str2 are not equal.
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
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
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
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)
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.
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
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
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
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
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
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
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.
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.
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.")
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.
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()
Output:-
Python teacher is teaching python.
Teacher is taking attendance.
Java teacher is teaching java.
Teacher is taking attendance.
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.
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
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
Example:-
class KodNest:
@staticmethod
def disp(msg):
print("Welcome To KodNest",msg)
KodNest.disp("code with KodNest")
Output:-
Welcome To KodNest code with KodNest
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
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.
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
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
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
Example:-
class Demo:
def disp(self):
print("Inside disp()")
d=Demo()
d.disp()
Output:-
Inside disp()
Example:-
class Demo:
def __init__(self,name,age):
self.name=name
self.age=age
def disp(self):
print("Inside disp()")
d=Demo("Rahul",27)
print(d.name,"",d.age)
d.disp()
Output:-
Rahul 27
Inside disp()
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
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
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'
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.
Example:-
class KodNest:
def disp(self):
print("Welcome To KodNest")
k=KodNest()
k.disp()
Output:-
Welcome To KodNest
Example:-
class KodNest:
def __disp(self):
print("Welcome To KodNest")
k=KodNest()
k.__disp()
Output:-
Error
Example:-
class KodNest:
def _disp(self):
print("Welcome To KodNest")
k=KodNest()
k._disp()
Output:-
Welcome To KodNest
Example:-
class Demo:
def __init__(self):
self.__x=10
self.__y=20
d=Demo()
print(d._Demo__x) #10
print(d._Demo__y) #20
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
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()
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
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
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
Example:-
class Calc:
def add(self,a,b):
print(a+b)
c=Calc()
c.add(10,20)
c.add("Kod","Nest")
Output:-
30
KodNest
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.
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
Example:-
When the object reference variable is printed, internally __str__() is invoked, which returns the
address of the reference variable of an object.
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__',
'__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']
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
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
__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.
__ifloordiv__(self, other) This method performs the floor division assignment a//=b.
__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.
__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.
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
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.
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]
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.
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.
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.
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
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.
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
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
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")
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.
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")
Output:-
Enter your age 10
You are not eligible for Driving License
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.
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()
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.
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.
TOPIC 18
PROGRAMS ON PYTHON
1. Write a python program to swap two numbers.
Program:-
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:-
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)
Output:-
Enter a number:10
10 is a positive number.
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
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.")
Output:-
Enter a number: 11
11 is a prime number.
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)
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:-
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
Output:-
Enter a number: 5
The factorial of 5 is 120
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
Output:-
Enter value of n:8
The fibonacci sequence of the numbers is:
0
1
1
2
3
5
8
13
Output:-
Enter first number: 5
Enter second number: 8
The L.C.M. of 5 and 8 is 40
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)
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
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:-
Output:-
Elements of original array:
10
20
30
40
50
Elements of new array:
10
20
30
40
50
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
Output:-
Original array:
10 20 30 40 50
Array in reverse order:
50 40 30 20 10
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=" ");
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
def fun(str):
str1 = ""
for i in str:
str1 = i + str1
return str1
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.
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'>
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
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
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
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)
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
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]
31. Write a python program to check whether the given strings are anagram or not.
Program:-
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:-
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
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:-
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.
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:-
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