RN Reddy Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 312
At a glance
Powered by AI
The key takeaways are that Python can be used for data science, machine learning, web development and more. It has both procedural and object-oriented capabilities.

The main numerical data types in Python are int and float. Python is dynamically typed.

The main operators in Python are arithmetic, relational, logical, membership and identity operators.

INDEX

1.Core Python - 3
2.Adv.Python - 137
3.Interview Questions - 231
4.Logical Programs - 259
.
CORE
PHTHON
.
ADV
PHTHON
.
1. What is PYTHON?
A. PYTHON is a Programming Language.
2. Who introduced python?
A.Gudio Van Rossum introduced python in the year 1989,he was from NetherLands.

3. Why python is so popular?


A. Because python is implementing in multiple areas like Data
Science,MachineLearning,DeepLearning,Devops,AWS,Big Data and soon……..

4. Why python is using in multiple areas?


A. Due to the Good features of python.

5. Write the features of python?


A.Features of Python:
• Python is very easy programming language.
• Python is case sensitive language.
• Python is general purpose programming language.
• Python is cross platform programming language.
• Python is open sourced programming language.
• Python is a procedural oriented and object oriented programming language.
• Python is modular programming language.
• Python is dynamic typed programming language.
• Python is interpreter based programming language.
• Python is an Embedded programming language.

6. Is python procedural oriented or object oriented programming language?


A. Python is both procedural oriented and object oriented programming language.

7. How can we say python is a procedural oriented?


A. Procedural oriented is a collection of functions, without class and object in python we can write
programs by functions.

8. Do we have main method in python?


A. Internally the main method is processed by the interpreter, we don’t have main method in code.

9. How many numerical data types in python?


A. Only one numerical data type i.e., int.

10. How many floating point data types in python?


A. Only one floating point data type i.e., float.

11. How can we say python is a dynamic typed programming language?


A. It is dynamic typed because we don’t require to declare any data type.

1
12. Is Python is compiler based or interpreter based?
A. Python is a interpreter based programming language.

13. How we can say python is an embedded programming language?


A. It can be integrated both in java and .net.

14. Can we integrate python code in java ? If yes, How?


A. Yes we can by using ‘JYTHON’ software.

15. Can we integrate python code in .net? If yes, how?


A. Yes we can by using ‘IRON PYTHON’ software.

16. what is variable?


A. A field which represents a value which can be changed is called as variable.

17. What are the Build -in-functions in python?


A. The built in functions are:
• Print()
• Type()
• Id()

18. How to accept input from the user?


A. By using input() function.

19. What is an operators?


A. An operator is used to perform the operation on data.

20. What are the operators in python?


A. In python we have 9 operators.
• Assignment operator.
• Arithmetic operator.
• Relational operator.
• Logical operator.
• Membership operator.
• Identify operator.
• Bitwise operator.
• Bitwise assignment operator.

20. What are Assignment operators?


A. An assignment operator is used to assign a value to variable.
Syntax: <variable>=<value>
Ex: x=10

2
21. What are Arithmetic operators?
A. Arithmetic operators are used to perform mathematical operations.
Operator Operation Example
+ Addition 4+2=6
- Subtraction 4-2=2
* Multiplication 4*2=8
/ Division 4/2=2.0
// Floor Division 4//2=2
% Modulation 4%2=0
** Power 4**2=16

22. What are Arithmetic Assignment operators?


A.An arithmetic assignment operator performs
1. Arithmetic operation.
2. Assignment operation.
Operator Operation Example Meaning
+= Addition a+=b a=a+b
-= Subtraction a-=b a=a-b
*= Multiplication a*=b a=a*b
/= Division a/=b a=a/b
//= Floor Division a//=b a=a//b
%= Modulation a%=b a=a%b
**= Power a**=b a=a**b

23. What are relational operator?


A. Relational operator checks a condition and return a Boolean value (true or false).
operators operations
< Less than
<= Less than or equal to
== Equals to
!= Not equals to
> Greater than
>= Greater than or equal to

24. What re logical operators?


A. A logical operators checks multiple conditions at a time and return Boolean value. Logical opera-
tors are:
1. and logical operator: "and" logical operator returns true when all given conditions are true,
otherwise false.
2. or logical operator: "or" logical operator returns true if atleast 1 condition is true within given
conditions, otherwise false.
3. not logical operator: not(true)->false
not(false)->true

3
25. What is membership operators?
A. Membership operators used to check whether given member is existed or not. If existed true is
returned otherwise false is returned.The following are membership operators in python:
1. in
2. not in

26. What is Identity operators?


A. Identity operators returns true if multiple objects have same id(identity number) otherwise return
false.The following are the identity operators:
1. is
2. is not

27.What is bitwise operators?


A. Bitwise operators are used to perform the operations on bits.
• &And bitwise operator
• |or bitwise operator
• ^xor bitwise operator
• >>right shift bitwise operator
• <<left shift bitwise operator
• ~one's compliment bitwise operator

28. What is bitwise assignment operator?


A. The following are the bitwise assignment operators.
• &=
• |=
• ^=
• >>=
• <<=

29. What are the datatypes in Python?


A. Datatypes are classified into 3 types.They are

• Fundamental Datatypes

• Collection Datatypes

• Other Datatypes

4
30. What are Fundamental Data types?
A. Fundamental datatypes are called as primary datatypes.These datatypes are main datatypes in
python.There are 5 types of Fundamental datatypes they are:
• int

• float

• str

• bool

• complex

31. Which data belongs to int in python?


A.In python we have only on numerical datatype i.e., int.This datatype represents a numerical value
which dosen’t have fractional part.

32.When we will go for int?


A.Whenever we want to store a numerical data which has no fractional part.

33.Which data belongs to float in Python?


A.A number which is having fractional value,which can be +ve or -ve.

34.When we will go for float?


A.Whenever we want to store a data which is having fractional part.

35.Which data belongs to string in python?


A.Collection of characters which is enclosed with single quotes(' ') or double quotes(" ") or triple
quotes(''' ''').

36.When we will go for string?


A.Whenever we want to store a character or group of characters.

37.What is the differences between single quotes , double quotes, triple quotes?
A.Using single quotes(' ') and double quotes(" ") we can represent only single line but using triple
quotes(''' ''') we can represent multiline string.

38.What is the difference between double quotes(" ") and single quotes (' ')?
A.There is no difference but whenever we want to highlight a substring within string we will use sin-
gle quotes for substring and double quotes for full string.

ex: a="rama is a 'good' boy"

print(a)

o/p: rama is a 'good' boy

39.Which data belongs to bool ?


A.bool represent either True value or False value.
True will be storing as binary 1
False will be storing as binary 0 in memory.

5
40.When we will go for bool?
A.Whenever we want to have True or False value.

41. Which data belongs to complex?


A.This datatype we will not use in business applications .we will use in Scientific applications.

42.When we will go for complex?


A.Whenever we are having any Scientific application.

43.What is typecasting?
A.Converting from one datatype to another datatype is called typecasting.

44.How many types of typecasting methods are there in python?


A.Python will support following typecasting methods:

• int()

• float()

• str()

• bool()

• complex()

45.What is int()?
A.int() method will convert the given value into int type except complex type.

46.What is float()?
A.float() method will convert the given any type value into float except complex type.

47.What is str()?
A.str() method will convert the any given value into str type.

48.What is bool()?
A.bool() method will convert given value into bool type.

49.What is complex()?
A.complex() method will convert the given value into complex type except string.

50. How to accept input from the user?


A. by using input() method.

51. How to handle Runtime errors?


A. To handle runtime errors in python we have 2 facilities
• By logic: To handle runtime erroes with the help of logic we should go with control state-
ments.
• By using Exeception handling mechanisam control statements.

52.What we can do by using control statements?


A.Using control statements we can control the program control according to our requirement.

6
53. When we will go for control statements?
A. Whenever we want to control the program control according to our requirement we will go for
control statements.

54. How many types of control statements are there?


A. In python we have 3 types of control statements.
• Conditional statements.
• Loops.
• Transfer statements.

55. What we can do by using conditional statements?


A. Using conditional statements we can execute a single statement or multiple statements based on
condition.

56. When we will go for conditional statements?


A. Whenever we want to execute single statements or multiple statements based on condition we
will go for conditional statements.

57. What are the types of conditional statements?


A. In python we have following conditional statements.
• Simple if
• If else
• If elif else
• Multiple if
• Nested if

58. What is the syntax for simple if?


A. if<condition1>:
st1

59.What is syntax forif else?


A. if<condition1>:
st1
else:
st2

60. What is the syntax for if elif else?


A. if<condition1>:
st1
elif<condition2>:
st2
elif<condition3>:
st3
else:
st4

7
61. What is the syntax multiple if?
A. if<condition1>:
st1
If<condition2>:
st2
If<condition3>:
st3

62. When we can do by using loops?


A. Using loops we can execute a single statements or multiple statements more than 1 times.

63. When we will go for loops?


A. Whenever we want to execute a single statements or multiple statements morethan 1 time we
will go for loops.

64. What are the types of loops?


A. In python we can implement following types of loops.
• For loop
• While loop
• While loop with else
• For loop with else

65. What is the syntax for ‘for loop’?


A. for<variable name> in range (<starting range>,<ending range>):
<logic>

66. When we will go for ‘for loop’?


A. Whenever we the number of iterations are fixed, go with ‘for loop’.

67. What is the syntax for while loop?


A. while<condition>:
<logic>

68. When we will go for ‘while loop’?


A. whenever the number of iterations are not fixed, go with ‘while loop’.

69. What is for with else?


A. Generally else part will be there for only conditional statements but in python else part is avail-
able for loops also.

70. What is the syntax for ‘for with else’?


A. for<variable name> in range(<first range>,<second range>):
<logic>
else:
<logic>

71. When we will go for simple if?


A. Whenever we have one option which we want to execute based on condition.

8
72. When we will go for if else?
A.Whenever we have two options, among two options if we want to execute one option based on
condition.

73. When we will go for if elif else?


A.Whenever we have more than two options, if we want to execute one option based on condition.

74. When we will go for Multiple if?


A. Whenever we have more than 2 options if we want to execute every option based on condition.

75. What is the syntax for ‘while with else’?


A. while<condition>:
<logic>
else:
<logic>

76. When we will go loop with else?


A. Whenever we want to implement else part for loops.

77. When we will go for transfer statements?


A. Whenever we want to transfer the program control from one place to another place.

78. What are the types of transfer statements?


A. There are 3 types
• Break
• Continue
• Pass

79. What is break?


A. break will transfer the program control out of the loop.

80. When we will go for break?


A. Whenever we want to transfer control out of the loop.

81. What is continue?


A. Continue will skip the current iteration of the loop.

82. When we will go for continue?


A. Whenever we want to skip the current iteration then we will go for continue.

83. What is pass?


A. using pass we can pass from 1 block to another block. This pass we will use especially at the time
of functions.

9
84. What are the string handling methods in python?
A. The string handling methods are:
• len()
• isupper()
• islower()
• upper()
• lower()
• isalnum()
• capitalize()
• count()
• startswith()
• endswith()
• find()

85. What is len()?


A. It will return number of characters within the string.
Ex: str1="rama"
Print(len(str1))
o/p:4

86.What is isupper()?
A. It will return true if the given string is in upper case, else false.
Ex: str1="rama"
str2="RAMA"
print("str1:",str1.isupper())
print("str2:",str2.isupper())
o/p: str1:false
str2:true

87. . What is islower()?


A. It will return true if the given string is in lower case, else false.
Ex: str1="rama"
str2="RAMA"
print("str1:",str1.islower())
print("str2:",str2.islower())
o/p: str1:true
str2:false

88. What is upper()?


A. It will convert the given string into upper case.
Ex: str1="rama"
print("str1:",str1.upper())
o/p: str1:RAMA

10
89. What is lower()?
A. It will convert the given string into lower case.
Ex: str1="RAMA "
print("str1:",str1.lower())
o/p: str1:rama

90. What is isalnum()?


A. It will return false only when there are any special characters in the given string, else true.
Ex: str1="rama"
str2="123"
str3="rama123"
str4="rama@123"
print("str1:",str1.isalnum())
print("str2:",str2.isalnum())
print("str3:",str1.isalnum())
print("str4:",str2.isalnum())
o/p: str1:true
str2:true
str1:true
str2:false

91. What is capitalize()?


A. It will convert 1st character of the string to upper case.
Ex: str1="rama"
print("str1:",str1.capitalize())
o/p: str1:Rama

92. What is count()?


A. It counts the repeated characters in the string.
Ex: str1="rama"
print("str1:",str1.count('a'))
o/p: str1:2

93. What is startswith()?


A. The given character and the string 1st character are same then it will return true, else false.
Ex: str1="rama"
print(str1.startswith('r'))
print(str1.startswith('m'))
o/p: true
false

94. What is endswith()?


A. The given character and the string last character are same then it will return true, else false.
Ex: str1="rama"
print(str1.startswith('a'))
print(str1.startswith('m'))
o/p: true
false

11
95. What is find()?
A. It will return the index of the character within the string.
Ex: str1="rama"
print("str1:",str1.find('r'))
o/p: str1:0

96.What is Collection?
A. Collection is representing collection of elements (objects).

97. How many types of collections in python?


A. In python there are 5 types of collections they are:
• list
• tuple
• set
• frozenset
• dict

98. What is list?


A. List is a collection of elements or objects, every element will be representing with one index value.
List is represented with square brackets and with comma to separate. List is mutable.
Ex: List1=[10,20,30,40,50]

99. What is mutable object?


A. A mutable object can be change ,with this we can say list values can be changed.
Ex: list[1]='rani'
Here 'sitha' is changed as 'rani'

100. Does list allow homogenous and heterogenous elements?


A. Homogenous elements means similar type elements.
Ex: list1=[10,20,30,40,50]
Heterogenous elements means dissimilar type elements.
Ex: list1=[10,10.2,'rama',true]

101. List of operations on list methods?


A. list methods are:
• index()
• eval()
• append()
• insert()
• extend()
• remove()
• pop()
• del[:]()
• reverse()
• sort()
• concatenation()

12
102. What is tuple?
A.It is a collection of objects. It is represented with parenthesis() and comma to separate values. It is
immutable object. Insertion order is fixed.Nested tuples also can be created.
Empnames=(value1,value2,value3………,value n)

103. List of operations in tuple method?


A. tuple methods are:
• tuple()
• len()
• count()
• index()
• min() and max()
• eval()

104. Write the differences between list and tuple?


A.
List Tuple
1. List is mutable. 1. Tuple is immutable.
2. List order is not fixed. 2. Tuple order is fixed.
3. We can insert an element in a list as a middle 3. We should insert an element to a tuple as a
element. last element.

105. What is set?


A. Set is a collection of objects. It is represented with curly brackets {} and with comma separate val-
ues. It dosenot support indexing. It is a mutable collection.
Ex: set1={10,20,30,40,50}

106. List of operations in set?


A. set methods are:
• set()
• copy()
• clear()
• union of set()
• intersection of set()

107. What is frozenset?


A.frozenset is a collection of objects. It is same as set but with one difference that is frozenset is im-
mutable but set is mutable.
Ex:myfrozenset={'raju','ravi','ramesh'}

108. List of opetrations on frozenset?


A. method operations on frozenset are:
• frozenset()
• copy()
• union()
• intersection()

13
109. What is dictionary?
A. Dictionary is a collection of "key : values" pairs. Dictionaries are mutable that means we can do
changes to dictionaries.
Syntax:<dict_name>={key1:value1,key2:value2,………………key n : value n}

110. List of operation on dictionary?


A. method operations on dictionary are:
• len()
• keys()
• values()
• clear()
• copy()

111. What is a function?


A.A function is a group of statements that together performs a task.

112. What is the advantage of functions?


A. The main advantage of functions is code reusability. The functions can also be called as methods,
procedures and subroutines.

113. What are the types of functions in python?


A. Python supports two types of functions
• built in functions
• user defined functions

114. What are Built in functions?


A. The functions what are coming along with python software automatically, are called as built in
functions or predefined functions or system defined functions.
Ex: print(), type(), input()……etc.

115. What are user defined functions?


A. The function which are developed by programmer explicitly according to business requirements,
are called as user defined functions.
Ex: #defining function
def Greet():
print("hello")
# calling function
Greet()
o/p: hello

116. What are the types of functions?


A. Types of functions are:
1. Function with parameters and with return values.
2. Function with parameters and without return values.
3. Function without parameters and with return values.
4. Function without parameters and without return values.

117. Can we return multiple values from a function?


A. In any programming language using a single function we can return a single value but in python
we have a special feature called with the help of single function we can return multiple values.

14
118. What are the types of arguments/parameters?
A. There are 6 types of arguments, they are:
1. Formal arguments
2. Actual arguments
3. Positional arguments
4. Keyword arguments
5. Default arguments
6. Variable length arguments

119. What is Formal arguments?


A. Called function argument are Formal arguments.

120. What is actual arguments?


A. Calling function arguments are actual arguments.

121. What is positional arguments?


A. At time of function calling actual parameters should be passed according to the position of the
formal parameter. The number of arguments and position of arguments must be matched. If we
change the order the result may change and if we change the number of arguments the we will get
error.

122. What is keyword arguments?


A. We can pass argument values by keyword i.e., by parameter names.

123. What is default arguments?


A. We can provide default values to arguments in this case if we didn't pass the value it will take de-
fault value.

124. What is variable length arguments/arbitrary arguments?


A. We can pass any number of arguments to function ,such type of arguments are called variable
length arguments. We can declare a variable length argument with * symbol as follows:
def Function1(*n):

125. What are types of variables?


A. Python supports 2 types of variables.
1. Global variables.
2. Local variables.

126. What are global variables?


A. The variables which are declare outside of function or outside of class are called Global variables.
These variables are accessed in all functions of that module. So, scope of the global variables is they
can be accessed throughout the module.

127. What are local variables?


A. The variable which declared inside a function case called as local variables. Local variables are
available only for the functions in which we declare i.e., from outside of function we can't access. So
scope of local variables are they can be accessed within the function only where they are declared.

128. What is module?


A. A module is a collection of variables, functions and classes.

15
129. What are the types of modules?
A. Types of modules are:
1. System defined modules
Ex: math, date time, string………..
2. User defined modules
To see the list of system defined modules help("modules")
o/p: It will display all the available system defined modules in python.

130. What is package?


A. Package is a collection of modules.

131. What are the steps to create a python package?


A. Working with python packages is really simple we need to do like below
• Create a directory
• Place modules with in the created directory.

132. What is lambda functions/lambda expressions?


A. With lambda functions we can write very less code. We can define lambda functions by using
lambda keyword.
Syntax: lambda argument_list : expression

133. What is Filter()?


A. We can use filter() function to filter required values.
Syntax: filter(function, sequence)

134. What is map()?


A. map() function is used to apply same functionality to every element.

135. What is reduce()?


A. reduce() function reduces the group of elements into a single element.
Syntax: reduce(function, sequence)

136. What are oops in python?


A. programming approaches are two types.
• Procedural oriented approach
• Object oriented approach

137. What is procedural oriented approach?


A. In procedural oriented approach, program is a collection of "functions".
A programming language which will follow the procedure oriented approach which is call as proce-
dural oriented programming language.
Ex: c language

138. What is object oriented approach?


A. A programming language which will follow object oriented programming language which is called
as object oriented programming language.
In object oriented approach, program is a "collection of classes".
Ex:c++, java, c#.net,python

16
139.What are oops principles?
A. Every oop language should follow the four principles. They are called oops principles.
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism

140. What we need to achieve oops principles?


A. To achieve above 4 principles every object oriented programming language should follow 2 oops
concepts.
• Class
• Object

141. What is class?


A. Class is a collection of states and behaviours. To define a class we have to use "class" keyword.

142. What is state?


A. State represents some values. State can be variable or constant.

143. What is self keyword?


A. self is a keyword which represent current class object in c# we have "this" keyword in python we
have "self" keyword.

144. What is behaviour?


A. Which represent functionality is called as behaviour. In python we can define following behav-
iours they are:
• Constructor
• Method

145. What is method?


A. A behaviour which represent some functionality, will execute whatever programmer will call is
called as method.

146. What are the types of methods?


A. In python we have 3 types of methods, they are:
• Instance method
• Class method
• Static method

147. What is instance method?


A. A method which is taking 'self' keyword as 1st parameter is called as instance method.
Instance method address will be available within the object. Due to that reason in instance method
we have to access by using object.
Syntax:def<methodname(self)>:
<logic>

17
148. What is an object?
A. An object is a instance of a class. Class is a logical representation object is a physical representa-
tion of a class.

149. What an object will contain?


A. An object will contain instance variable and address of instance methods.
Syntax:<objectname>=<classname()>

150. What is constructor?


A. A constructor is a special type of function which will execute at the time of object is creating. Con-
structor should define with one parameter that is self.
Constructor name should define as __init__(self)

151. What are the types of Constructors?


A. Constructors are 2 types
• Default constructor or parameter less constructor
• Parameterized constructor

152. What is default constructor?


A. While defining a constructor if we did't declare any parameter except self keyword is called as de-
fault constructor.
Syntax:def __init__(self):
<self.instance variable>=<value>
<self.instance variable>=<value>

153. What are the limitation of default constructor?


A. default constructor will initialize the same values to every object. To over come this we have to go
for parameterized constructor.

154. What is parameterized constructor?


A. While defining constructor if we initialize parameters which is called as parameterized construc-
tor.
Syntax:def __init__(self,par1,par2…..parn):
Self.instance variable 1=par1
Self.instance variable 2=par2

155. How to initialize instance variable?


A. By using constructor as well as we can initialize by using instance method.

156. When we will initialize instance variable by using constructor?


A. Whenever we want to initialize instance variable at the time object is creating.

157. When we will initialize instance variable by using instance method?


A. Whenever we want to initialize instance variable after object is created.

158. When we will go for local variable?


A. Whenever a field is required only within the method we will go for local variable.

18
159. When we will go for instance variable?
A. Whenever field is required for every object with different value but value can be changed ,we will
declare it as instance variable.

160. When we will go for static variables?


A. A field which is common for all the objects is called as static variable.

161. When class will load?


A. Whenever python interpreter required a class member.

162. When class will unload?


A. Whenever application execution is completed concern application all the classes will unload.

163. What is getter and setter?


A. getter and setter are special type of methods. Using setter we can initialize an individual instance
variable. Using getter we can retrieve value from an individual instance variable.
Setter should prefix with Set.
Getter should prefix with Get.
Syntax for setter:
def<setter name(self, <parameter name>)>:
<instance variable name>=<parameter name>
Syntax for getter:
def<getter name(self)>:
return<instance variable name>

164. What is inheritance?


A. Inheriting the members from one class to another class is called as inheritance.
Establishing the parent and child relation between 2 classes is called as inheritance.
Syntax: class BC:
//members
Class DC(BC):
//members

165. What are the types of inheritances in python?


A. In python we have various types of inheritances like below.
• Single inheritance
• Multiple inheritance
• Multi-level inheritance
• Multi-path inheritance
• Hierarchical inheritance
• Hybrid inheritance

166. What is single inheritance?


A. Inheritance from one class to another class is called as single inheritance.
Ex: class BC:
//members
class DC(BC):
//members

19
167. How to call instance method within the class?
A. We don't require to create object , we can access by using self keyword. Here self is nothing but
current class object.

168. How to call instance method outside the class?


A.with the help of object.

169. What is multi-level inheritance?


A. Inheritance from one class to another class from that class to some other class is called multi-level
inheritance.
Ex: class BC:
//members
class DC(BC):
//members
class TC(DC):
//members

170. What is multiple inheritance?


A. Inheriting from multiple base classes into single derived class is called as multiple inheritance.
Ex: class BC1:
//members
class BC2:
//members
class DC(BC1,BC2):
//members

171. What is multipath inheritance?


A. Inheriting from 1 base class to some derived classes and that derived classes inheriting to another
class is called as multipath inheritance.
Ex: class BC:
//members
class DC(BC):
//members
class TC(BC):
//members
class MC(DC,TC):
//members

172. What is Hierarchical inheritance?


A. Inheriting 1 base class into multiple derived classes is called as Hierarchical inheritance.
Ex: class BC:
//members
class DC(BC):
//members
class TC(BC):
//members
class MC(BC):
//members

20
173. What is hybrid inheritance?
A. Combination of any 2 inheritances is called Hybrid inheritance i.e., multilevel, multiple or multi-
ple, multipath is called hybrid inheritance.
Ex: class BC:
//members
class DC(BC):
//members
class TC(BC):
//members
class MC(DC,TC):
//members

174. What is the benefit of inheritance?


A. Reusability.

175. What is polymorphism?


A. It means one name many forms.
Implementing multiple functionalities with the same name is called polymorphism. That means im-
plementing multiple methods with the same name but every method behaviour will be different is
called polymorphism.

176. What are the types of polymorphism?


A. In python polymorphism are 2 types. They are:
• Overloading
• Overriding

177. What are the types in over loading?


A. There are 3 types
• Method overloading
• Constructor overloading
• Operator overloading

178. What is method overloading?


A. If 2 methods having same name with different arguments list then those methods are called
overloaded methods.

179. What is constructor overloading?


A. Implementing multiple constructors with different number of arguments is called as constructor
overloading.

180. What is operator overloading?


A. We can use same operator for multiple purpose which is nothing nut operator overloading.

181. What are the types of overriding?


A. We have 2 types of overriding.
• Method overriding
• Constructor overriding

21
182. What is method overriding?
A. Implementing super class method within the subclass with the same name and same signature is
called as method overriding.

183. What do you mean by same signature?


A. Number of parameters should be same.

184. What is constructor overriding?


A. Implementing the super class constructor and sub class constructor with the same signature is
called as constructor overriding.

185. What is super() method?


A. Using this we can call the super class constructor and super class instance method.

186.

22
1.Write a Python Program to print message:
Program:

print("hi")

OUTPUT:

2. Write a Python Program to print two message:


Program:

print("hi")

print("hello")

OUTPUT:

3. Write a Python Program to print three message:


PROGRAM:

print("Welcome To Python")

print("Welcome To Programing")

print("Welcome To Sathya Technologies")

OUTPUT:
4.Write a python Program to store a person information “Rama” into a one variable called
“name” and a person age 20 into a another variable called “age”.Print two values with the
help of variables.
PROGRAM:

name="rama"

age=20

print(name)

print(age)

OUTPUT:

5. Write a python Program to store a employee information i.e


empno=111,empname=”rama”and empsaal=1000 into a three variable they are eno,ename
and esal.Print the three values with the help of variables:
PROGRAM:

empno=123

empname="rama"

empSal=2000

print("Employee no is :",empno)

print("Employee name is :",empname)

print("Employee salary is :",empSal)

OUTPUT:
6.Write a Python program to store three subject marks60,70,80 into three variables they are
M1,M2,M3.Calculate total marks Store into one variable called totMarks and calculate
average marks store into another variable called avgmarks.Print the totalMark and avgmarks
with the help of message and variable.

PROGRAM:

m1=float(input("enter m1 marks:"))

m2=float(input("enter m2 marks:"))

m3=float(input("enter m3 marks:"))

totmarks=m1+m2+m3

avgmarks=totmarks/6

print("total marks are:",totmarks)

print("average marks are:",avgmarks)


OUTPUT:
7.Write a python program to store two product cost i.e 1000,2000 into two variables they are
P1,P2.Calculate total bill store into one variable called totbill and calculate 10% discount on
total bill and store discount in disc variable .Display the total variable after discount by using
message and variable.
PROGRAM:

p1=1000

p2=2000

totbill=p1+p2

disc=totbill*0.10

totbill=totbill-disc

print("total bill after discount is :",totbill)

OUTPUT:
8.Write a python program to store two product cost i.e 1000,2000 into two variables they are
P1,P2.Calculate total bill store into one variable called totbill .On total bill 20% discount and
store discount in disc variable .After discount calculate 30% tax on total bill.Display the total
bill by using message and variable.

PROGRAM:

p1=1000

p1disc=p1*0.10

p1=p1-p1disc

p1tax=p1*0.20

p1=p1+p1tax

p2=2000

p2disc=p2*0.20

p2=p2-p2disc

p2tax=p2*0.30

p2=p2+p2tax

totbill=p1+p2

tax=totbill*0.30

print("total bill is :",totbill)

print("total bill after 30% tax is :",tax)


OUTPUT:
9.Write a python program to store two product cost 1000,2000 into two variable they are
P1,P2.On P1 10% discount and 20% tax.On P2 20% discount and 30% tax.Calculate total bill
and store into one variable called totbill.Finally print total bill with message and variable.

PROGRAM:

p1=float(input("Enter p1 cost:"))

p2=float(input("Enter p2 cost:"))

p1disc=p1*0.10

p1=p1-p1disc

p1tax=p1*0.20

p1=p1+p1tax

print("p1 after disc and tax is:",p1)

p2disc=p1*0.20

p2=p2-p2disc

p2tax=p2*0.20

p2=p2+p2tax

print("p2 after disc and tax is:",p2)

totbill=p1+p2

print("totbill is:",totbill)

OUTPUT:
10.Write a python program to accept two number from the users store into a variable a and b
and perform addition.Display addition result.
PROGRAM:

a=input("Enter first number:")

b=input("enter second number:")

c=int(a)+int(b)

print("Addition result is:",c)

OUTPUT

11. Write a python program to accept two product cost P1,P2 .Calculate total bill .On total bill
10% discount.Display the total bill after discount.

PROGRAM:

p1=float(input("Enter p1 cost:"))

p2=float(input("Enter p2 cost:"))

##p3=float(input("Enter p3 cost:"))+p3

totbill=p1+p2

disc=totbill*0.10

totbill=totbill-disc

print("Total bill is:",totbill)

OUTPUT:
13.Write a python program to accept two product cost P1,P2.On P1 10% discount and on P2
20% discount .Calculate total bill.On total bill 30% tax .Display P1,P2 cost after discount and
display tax .Finally display total bill after tax.

PROGRAM:

p1=float(input("Enter p1 cost:"))

p2=float(input("Enter p2 cost:"))

p1disc=p1*0.10

p1=p1-p1disc

print("p1 after disc is:",p1)

p2disc=p1*0.20

p2=p2-p2disc

print("p2 after disc is:",p2)

totbill=p1+p2

tax=totbill*0.30

print("tax is",tax)

totbill=totbill+tax

print("totbill is:",totbill)

OUTPUT:
14.Write a python Program to accept two numbers and perform division and display division
result.
PROGRAM:

a=input("Enter first number:")

b=input("enter second number:")

c=int(a)/int(b)

print("Division result is:",c)

OUTPUT:

15.Write a python Program to accept two numbers and perform substraction and display
substraction result.
PROGRAM:

a=input("Enter first number:")


b=input("enter second number:")

c=int(a)-int(b)

print("Substraction result is:",c)

OUTPUT:

16.Write a python Program to accept two numbers and perform multiplication & division and
display result.
PROGRAM:

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

b=int(input("enter second number:"))

c=a/b

print("Division result is:",c)

c=a*b

print("Multiplication result is:",c)

OUTPUT:
17.Divide by zero.

PROGRAM:

a=int(input("Enter first Number:"))

b=int(input("Enter second number:"))

while b==0:

b=int(input("pls enter second number other than zero..."))

c=a/b

print("Div result is",c)

OUTPUT:

18.Write a python program to compare i and j value by using if else.

Program:

i=int(input("Enter i value"))
j=int(input("enter j value"))
if i>j:
print("i is greater than j")
else:
print("j is grater than i")
OUTPUT:
19. Write a python program to compare i and j value by using if elif else.

PROGRAM:

i=int(input("Enter i value"))

j=int(input("enter j value"))

if i>j:

print("i is greater than j")

elif j<i:

print("j is grater than i")

else:

print("i is eqyal to j")

OUTPUT:
20.Write a python program to accept age from the user and display user status:

i)age>=58:senior citizen

ii)age between 25 to57 : working citizen

iii)age between 16 to 24: collage student

iv)age between 4 to 15 : school kid

v)age between 1 to 3 :playing kid

vi)Invalid age

PROGRAM:

age=int(input("enter your age:"))

if age>=58:

print("senior citizen")

elif age>=25 and age<58:

print("working citizen")

elif age>=16 and age<=24:

print("college student")

elif age>=4 and age<=15:

print("school kid")

elif age>=1 and age<=3:

print("playing kid")

else:

print("invalid age")

OUTPUT:
21.Write a python program to accept a number from 0 to 9 print in letters.

PROGRAM:

number=int(input("enter your number:"))

if number==0:

print("zero")

elif number==1:

print("one")

elif number==2:

print("two")

elif number==3:

print("three")

elif number==4:

print("four")

elif number==5:

print("five")

elif number==6:

print("six")

elif number==7:

print("seven")

elif number==8:

print("eight")

elif number==9:

print("nine")

else:
print("invalid input.....")
OUTPUT:

22.Write a python program to accept three subject marks i.eM1,M2,M3.Calculate total marks
store into a variable called totmarks and calculate average marks store into another variable
avgmarks and display the result:

i)if he got less than 35 marks in any one subject ,student is fail.

ii) if avgmarks>=60,he is first class.

iii)if avgemarks between 50 to 59 ,student is second classs.

iv)if avgmarks between 35 to 49,student is third class.


PROGRAM:

M1=int(input("Enter M1 marks:"))

M2=int(input("Enter M2 marks:"))

M3= int(input("Enter M3 marks:"))

totmarks=M1+M2+M3

avgMarks=totmarks/3

if M1<35 or M2<35 or M3<35:

print("Result is fail")

if avgMarks>60:

print("Result is First Class")

elif avgMarks>50:

print("Reult is second class")

elif avgMarks>35:

print("Result is third class")

OUTPUT:
23. Implement comparing I and j by using nested if conditions.

PROGRAM:

i = int(input("Enter i value:"))

j = int(input("Enter j value:"))

if i>j:

print("i is greater than j")

else:

if i<j:

print("j is greater then i")

else:

print("i is eqaul to j")

OUTPUT:

24.Write a python program to print upto given range by using for loop.
PROGRAM

i=int(input("Enter ur range:"))
for i in range(1,i+1):

print(i)

OUTPUT:

25.Write a program to print a number in reverse from 5 to 1:


PROGRAM:

for i in range(5,0,-1):

print(i)

#OUTPUT:

26. Write a python program to print odd number from 1to 10 by using for loop.

PROGRAM:

for i in range(1,10):

if i%2!=0:
print(i)

OUTPUT:

27. Write a python program to print 10 to 50 by using for loop.

Expected output:

10
20
30
40
50
PROGRAM:
for i in range(10,60,10):
print(i)
OUTPUT:

28. Write a python program to print even numbers in reverse by using for loop.
Expected output:
10
8
6
4
2
PROGRAM:
for i in range(10,0,-1):
if i%2==0:
print(i)
OUTPUT

29. Write a python program to print 1 to 5 like below.

Expected Output:

1 2 3 4 5

PROGRAM:

for i in range (1,6):

print(i,end=" ")

OUTPUT:

30.Write a python program to print like below by using while loop:

Expected output: 1
3
5
7
9
PROGRAM:
i=1
while i<=9:
print(i)
i=i+2
OUTPUT:
31. Write a python program to print like below by using while loop:

Expected output: 10
8
6
4
2
PROGRAM:
i=10
while i>0:
print(i)
i=i-2
OUTPUT:

32. Write a python program to print like below by using while loop:
Expected output: 1
2
3
4
5
6 7 8 9 10
PROGRAM:
i=1
while i<=6:
print(i)
i=i+1
while i<=10:
print(i,end=' ')
i=i+1
OUTPUT:

33.Write a python program to display output like below:


Expected Output:
12345
6
7
8
9
10
PROGRAM:
for i in range (1,11):
if(i<5):
print(i,end=" ")
else:
print(i)
OUTPUT:
34.Write a python program to print like below:
Expected output:
1 2 3 4 5
6
7
8
9
10
11 12 13 14 15
for i in range(1,16):
if i<5:
print(i,end=" ")
elif i<=10:
print(i)
else:
print(i,end=" ")
OUTPUT:

35. Write a python program to print like below :


Expected output:
1
22
333
4444
55555
PROGRAM:
i=1
while i<=5:
j=1
while j<=i:
print(i,end='')
j=j+1
print()
i=i+1
OUTPUT:

36. Write a python program to print like below:


Expected output: 55555
4444
333
22
1
PROGRAM:
n=int(input("Enter your range:"))
i=n
while i>=1:
j=i
while j>=1:
print(i,end='')
j=j-1
print()
i=i-1
OUTPUT:
37. Write a python program to print like below:
Expected output:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

PROGRAM:
for i in range(1,5+1):
for j in range(1,i+1):
print(j,end=" ")
print(" ")
OUTPUT:

38. Write a python program to print like below :

Expected output:

5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
PROGRAM:
for i in range(5,0,-1):
for j in range(i,0,-1):
print(j,end=" ")
print(" ")
OUTPUT:

39. Write a python program to print like below:


Expected output:

1
2 3
4 5 6
7 8 9 10
PROGRAM:

a=1
for i in range(1,5):
for j in range(1,i+1):
print(a,end=" ")
a=a+1
print()
OUTPUT:
40. Write a python program to print like below:
Expected output:

1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
PROGRAM:
for i in range(1,6):
for j in range(i,6):
print(j,end=" ")
print("")

OUTPUT:

41. Write a python program to print like below by using while loop:
Expected output:

1234
567
89
10
PROGRAM:
a=1
for i in range(1,5):
for j in range(1,i+1):
print(a,end=" ")
a=a+1
print()
OUTPUT:

43. Write a python program to print like below by using while loop:
Expected output:

12345
1234
123
12
1
PROGRAM:
i=5
while i>=1:
j=1
while j<=i:
print(j,end='')
j=j+1
print()
i=i-1
OUTPUT:
44. Write a python program to accept a string print in reverse :

PROGRAM
str1= input("Enter your string:")

str1[::-1]

print("Reverse string is:",str1[::-1])

OUTPUT:

Enter your string:rama


Reverse string is: amar
45.Write a Python program to print Fibonacci Series.

PROGRAM

n=int(input("Enter your range:"))

a=0

b=1

c=0

while a<n:

c=a+b

print(a,end='')

a=b

b=c

OUTPUT:
46.Write a python program to display list ,sum & number of even numbers up to given range.

PROGRAM:

n=int(input("Enter range:"))

evensum=0

evencount=0

for i in range (1,n+1):

if i%2==0:

evensum+=i

evencount+=1

print(i)

print("Sum of even number:",evensum)

print("Count of even number:",evencount)

OUTPUT:
47. Write a python program to display list ,sum & number of odd numbers up to given range.

PROGRAM:

n=int(input("Enter range:"))

oddsum=0

evencount=0

for i in range (1,n+1):

if i%2!=0:

oddsum+=i

evencount+=1

print(i)

print("Sum of even number:",oddsum)

print("Count of even number:",evencount)

OUTPUT:
48.Write a python program to accept a number check is it prime or not.

PROGRAM:

n=int(input("Enter your number:"))

ctr=0

for i in range(2,n):

if(n%i==0):

ctr=ctr+1

if(ctr==0):

print("it is prime number")

else:

print("it is not prime number")

OUTPUT:

49. Write a python program to display list of prime number ,sum of prime number & number
of prime numbers up to given range.

PROGRAM:

n=int(input("Enter your Range:"))

s=0

c=0

print("List of prime numbers is:")

for m in range(1,n+1):

x=int(m/2)

ctr=1
for i in range(1,x+1):

if(m%i==0):

ctr=ctr+1

if(ctr==2):

print(m)

s=s+m

c=c+1

print("Sum of prime Numbers is:",s)

print("Number of Prime numbers is:",c)

OUTPUT:
50.Write a python program to accept a number and print in reverse.

PROGRAM:

n=int(input("Enter your number:"))

rev=0

while(n>0):

a=n%10

rev=rev*10+a

n=n//10

print("Reverse number is:",rev)

OUTPUT:

51.Write a python program to accept a string print in reverse .

PROGRAM:

str1= input("Enter your string:")

str1[::-1]

print("Reverse string is:",str1[::-1])

OUTPUT:
52.Write a python program to accept a string and check is it palidrom or not.

PROGRAM:

n=input("Enter your String : ")

x=n[::-1]

if x==n:

print("It is palindrome")

else:

print("It is Not palindrome")

OUTPUT:

53.Write a python program to accept a number and check is it palidrom or not

PROGRAM:

n=input("Enter your Number")

x=n[::-1]

if x==n:

print("It is palindrome")

else:

print("It is Not palindrome")


OUTPUT:
54.Write a python program to accept two numbers implement swapping.

PROGRAM:

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

b=int(input("Enter b value:"))

a,b=b,a

print("a value is",a)

print("b value is",b)

OUTPUT:
55.Write a python program to accept a string and print length of string.

Expected Output:

Enter your string:Rama

Number of characters are:4

PROGRAM:

i=input("Enter your string:")

print("number of characters are:",len(i))

OUTPUT:

56.Write a python program to display sum of digits of given numbers.

Expected Output:

Enter your number:123

Sum:6

PROGRAM:

i= int(input("Enter your number:"))

rev=0

rem=0

while(i!=0):

rem=i%10

rev=rev+rem

i=i//10

print("sum of numbers is:",rev)

OUTPUT:
#LIST PROGRAM:

57.Write a python program to create a list collection and print:

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

PROGRAM:

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

print(list1)

OUTPUT:

58.write a python program to print 10 to 50 by using loop:

Expected Output:

10

20

30

40

50

PROGRAM:

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

for i in list1:

print(i)

OUTPUT:
59.Printing the list of element in reverse.

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

PROGRAM:

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

print(list1[::-1])

OUPTPUT:

60.Accepting the number from the users & appending the list.

Program:

mylist=[]

for i in range(1,6):

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

mylist.append(j)

print("My list elements are:")

for i in mylist:

print(i,end=" ")

OUTPUT:
61.Write a python program to perform operation on list by using list method.

Program:

mylist.append(60)

print(mylist)

#insert()

mylist.insert(3,70)

print(mylist)

#extend()

mylist.extend([80,90,100,110])

print("after extending,elements in list are:",mylist)

#range()

mylist[4:4]=range(31,36)

print(mylist)

#remove()

mylist.remove(10)

print("after removing 10 elements are:",mylist)

#pop()
mylist.pop()

print("pop elements based on index:",mylist.pop(2))

#del()

del(mylist[1:3])

print("after deleting elements are:",mylist)

#reverse()

mylist.reverse()

print("reverse list is:",mylist)

#sort()

mylist.sort()

print("sorted elements are:",mylist)

#copy()

list2=mylist.copy()

print("copy list is :",list2)

OUTPUT:

62.Write a python program to create one tuple by displaying the elements.

PROGRAM:

Empnos=(10,20,30,40,50)

print(Empnos)

OUTPUT:
63. Write a python program to perform operation on tuple by using tuple method.

PROGRAM:

#tuple()

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

mytuple=tuple(mylist)

print(mytuple)

#count()

print("50 appears",mylist.count(50),"times")

#index()

print("index value of 30 is:",mylist.index(30))

#min() and max()

print("minimun value is:",min(mylist))

print("maximum value is:",max(mylist))

#eval()

mytuple1=eval(input("Enter your elements:"))

print(mytuple1)

OUTPUT:
64.Write a python program to perform various operation on set collection with buit in
methods.

PROGRAM:

#set()

mylist1={10,20,30,40}

myset=set(mylist1)

print("set elements are:",myset)

#copy()

mylatestset=myset.copy()

print("copy elements are:",mylatestset)

#Uions of set

mylist2={10,20,50,60,70}

set3=mylist1.union(mylist2)

print("union of set are:",set3)

#intersection of set

set4=mylist1.intersection(mylist2)
print("intersection elements are:",set4)

OUTPUT:

65.Write a python program to perform various operation on frozenset collection with buit in
methods.

PROGRAM:

#set()

mylist1={10,20,30,40}

myset=set(mylist1)

print("set elements are:",myset)

#copy()

mylatestset=myset.copy()

print("copy elements are:",mylatestset)

#Uions of set

mylist2={10,20,50,60,70}

set3=mylist1.union(mylist2)

print("union of set are:",set3)

#intersection of set

set4=mylist1.intersection(mylist2)

print("intersection elements are:",set4)


OUTPUT:

66.Write a python program to perform various operation on Dictionary collection with buit in
methods.

PROGRAM:

fruitdict={111:'apple',222:'Banana',333:'chery'}

print(fruitdict)

#len()

print("length is:",(len(fruitdict)))

#keys

print("key is:",fruitdict.keys())

#values()

print("value is:",fruitdict.values())

#copy()

mydict=fruitdict.copy()

print("copy elements is:",mydict)

OUTPUT:
67.Writw a python program for function with parameter and with return value.

PROGRAM:

def Add(a,b):

c=a+b

return c

x=int(input("Enter 1st no:"))

y=int(input("Enter 2nd no:"))

res=Add(x,y)

print("Addition result is:",res)

OUTPUT:
68.Writw a python program for function with parameter and without returning value.

PROGRAM:

def Sub(x,y):

z=x-y

print("Substraction Result is",z)

a=int(input("Enter First Number:"))

b=int(input("Enter Second Number:"))

Sub(a,b)

OUTPUT:

69.Writw a python program for function without parameter and with return value.

PROGRAM:

def GenerateEmpNo():

return 111

empno=GenerateEmpNo()

print("generated emplyoee no is:",empno)

OUTPUT:
70.Writw a python program for function without parameter and not returning any value.

PROGRAM:

def Greet():

print("Good Morning")

#calling Function

Greet()

OUTPUT:
71.Writw a python program for returing multiple values from a function.

PROGRAM:

def Multiplication(a,b):

c=a+b

d=a-b

e=a*b

f=a/b#will return FRACTIONAL VALUE

g=a//b#will not return FRACTIONAL VALUE

h=a%b

return c,d,e,f,g,h

num1=int(input("Enter first Number:"))

num2=int(input("Enter Second Number:"))

res=Multiplication(num1,num2)

print("All calculations result is:",res)

OUTPUT:
72.Write a python program to create user defined module.

PROGRAM:

def Add(a,b):

print("Sum=",a+b)

def Sub(a,b):

print("Substraction=",a-b)

def Mul(a,b):

print("Multiplication=",a*b)

def Div(a,b):

print("Division=",a/b)

save above program as:calc.py

to consume above module we will write below code:

import Calc

i=int(input("Enter First Value:"))

j=int(input("Enter Second Value:"))

Calc.Add(i,j)

Calc.Sub(i,j)

Calc.Mul(i,j)

Calc.Div(i,j)

Save as”MYclient.py”

OUTPUT:
73.Write a puython program for package.

PROGRAM:

// STEP 1:creating first Module:

def addition(a,b):

return a+b

def substraction(a,b):

return a-b

def Multiplication(a,b):

return a*b

def Division(a,b):

return a/b

def Modulation(a,b):

return a%b

//save as”ao.module.py”

STEP 2:creating another module.

def string_length(string1):
return len(string1)

def string_reverse(string):

return string[::-1]

save abobe code as”string.module.py”

STEP 3:Importing and Consuming above two module

>>consuming the above package.

>>write the below code.

import ao_module as a

import string_module as s

i=int(input("Enter first Integer:"))

j=int(input("Enter second integer:"))

print("adition=",a.addition(i,j))

print("substraction=",a.substraction(i,j))

print("Multiplication=",a.Multiplication(i,j))

print("Division=",a.Division(i,j))

print("Modulation=",a.Modulation(i,j))

print("*"*40)

string1=input("Entera string:")

print("String Length is:",s.string_length(string1))

string2=input("Enter another string:")

print("Reversed String is:",s.string_reverse(string2))

OUTPUT:
74.Write a python program to define a lambda function to find square of even numbers.

PROGRAM:

square=lambda n:n*n

print("Square of 4 is:",square(4))

print("Square of 2 is:",square(2))

OUTPUT:

75. Write a python program to find the sum of two given numbers.

PROGRAM:

sum=lambda a,b:a+b

print("Sum of numbers is:",sum(10,20))

OUTPUT:
76. Write a python program to find the square of given numbers.

PROGRAM:

list1=[100,200,300,400,500]

list2=list(map(lambda x:x*x,list1))

print(list2)

OUTPUT:

77.Write apython program to filter the list element by using Lambda functions.

PROGRAM:

list1=[10,20,30,40,50,60,70,80,90,100]

even=list(filter(lambda x:x%2==0,list1))

print(even)
OUTPUT:

You might also like