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

Python Interview Questions

Python interview

Uploaded by

Pavan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Python Interview Questions

Python interview

Uploaded by

Pavan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Python interview questions

What is the difference between list and tuple?


List Tuple
1. List is created by using [ ] symbol. 1. Tuple is created by using ( ) symbol.
2. List elements are mutable 2. Tuple elements are immutable
eg:
a = [10,20,30] b = (100,200,300)

What is set?
Set is created by using { } symbol.
Set stores elements in random order fashion.
Set doesn’t allow duplicate elements.
eg: c = {‘palle’, ‘python’, ‘bangalore’}
What is a dictionary?
dictionary is used to store key-value pairs.
Keys should be unique, and values can be duplicate.

eg:

d={
‘email’ : ‘[email protected]’,
‘pw’ : ‘abcd123’,
‘course’ : ‘python’,
‘duration’ : 90
}
How will you create array in python?
we can create array in python by importing array module.
eg:
Import array
e = array.array( ‘i’ , [10,20,30,40] )
print(e)
What is the difference between array and list?

array list
In array we can store only In list we can store homogeneous and
homogeneous elements. heterogeneous elements.
What is the difference between list and dictionary?
list dictionary
List is an ordered collection of elements, Dictionary is used to store pairs of
where the elements are stored on index elements
basis.
We can access list elements using index. We can access dictionary values with
keys.
Note : same difference can be told for tuple vs dictionary also.

What is the difference between list and set?


list set
List is an ordered collection of elements, Set elements are stored in random order.
where the elements are stored on index
basis.
We can access list elements using index. We can’t access set elements using index.
List allows duplicate elements. Set doesn’t allow duplicate elements.

Note : same difference can be told for tuple vs set also.


What is list comprehension?
list comprehension is a concise way to create a new list from
values of existing list.
eg:
f = [10,20,30]
g = [item*2 for item in f]
print(g)

What is default parameter?


A function parameter can have a default value. If the function
is called without passing value to that parameter, then that
parameter will get that default value.
eg:
def m1(x,y,z=10):
print(x,y,z)
In the given example z is default parameter.
m1(1,2)
what is args?
arguments is represented with single *
by using *args programmer can pass variable
number of arguments to a function.

eg:
def m2(*x):
print(x)

m2(100,200,300)
what is kwargs (key word arguments) ?
keyword arguments is represented with **
by using **kwargs programmer can pass
variable number of key worded arguments (or
pairs of elements)

eg:
def m3(**x):
print(x)

m3(name=‘palle’, course=‘python’, duration=90)


What is the difference between args and
kwargs?
args kwargs

arguments is represented with Keyword arguments is


single * symbol before the represented with ** symbol
parameter. before the parameter.
by using args programmer can by using kwargs programmer
pass variable number of can pass variable number of
arguments to a function. key worded arguments (or
pairs of elements) to a
function
What is lambda or lambda expression?
lambda expression is an un-named function which
contains single expression code
lambda expressions are used for passing a call back
function as parameter.
eg:
m4 = lambda x, y : x + y
print( m4(10,20) )

What is a generator?
Generator is used create an iterator (of values) which we can
iterate and read elements one by one using a loop.
What is a regex or regular expression?
1. regular experession is a string pattern that we want
to find in a given text.
2. re is a predefined module in python which contains
regular expression functions.
eg:
import re
re.search(‘all’ , ‘palle’)

search() function is used to search the first occurrence of a word


in the given text.
what is the use of split() function?
1. by using split function we can split a string into
words and store into a list.
2. split() function expects a separator as parameter,
based on which you can split the string.

eg:
h = ‘palle technologies python bangalore’
mylist = h.split(‘ ‘)
print(mylist)
it will display output as [‘palle’ , ’technologies’ , ’python’ , ’bangalore’]
what is the use of join() function?
by using join function we can join the list of elements
into a string.

eg:
j = [‘palle’, ‘technologies’, ‘python’, ‘bangalore’]
k = ‘ ‘.join(j)
print(k)
it will display output as palle technologies python bangalore.
What is decorator?
decorator is used to modify the behavior of a function,
without explicitly changing it’s structure.

eg:
def wrapper(fun): In the above code wrapper
def inner(): is the decorator for display() function

print(‘hello’) If we call display() function then output will be


Hello
fun() Display function
print(‘bye’) bye
return inner

@wrapper
def display():
print(‘display function’)
What is Object oriented programming
language?
• Any Programming language which supports
below 6 features is considered as OOP
language

1. Class
2. Object
3. Encapsulation
4. Abstraction
5. Inheritance
6. Polymorphism
What is a class
class is a virtual entity.
class acts as blue print for objects.
class is used for storing related variables and methods.
eg: class Student:
def study(self):
print(‘student is studying’)

What is an object
Object is a real world entity.
eg:
s1 = Student()
what is constructor or init() ?
by using constructor we can assign data into objects or we can
initialize objects

eg:

class Bank:
def __init__(self, name, acno):
self.name = name
self.acno = acno

b1 = Bank(‘ramesh’, 12345)
What is encapsulation?
binding logically related data and functions in a
common related place, is known as encapsulation.
eg:
class Doctor:
def __init__(self, name, exp):
self.name = name
self.exp = exp
def suggestMedicine(self):
print(‘doctor will suggest medicine to patient’)

In the above example, we are storing all the doctor related


data and doctor related methods in one class. So we can
say Doctor class is following encapsulation.
What is inheritance?
inheritance allows us to access parent class variables
and methods, in child class.
Inheritance reduces code duplication.

eg:
class Bank:
def addaccount(self):
pass #contains code for adding new account in the bank

class HdfcBank(Bank):
def rateofinterest(self):
pass #contains code for calculating rate of interest
What is method overriding?
1. having same method name in parent class and child class, with
same number of parameters, is known as method overriding.
2. overriding is used for changing the behavior of parent class
method in the child class.

eg:
class Animal:
def run(self):
print(‘animal runs on 4 legs’)

class Human(Animal):
def run(self):
print(‘human runs on 2 legs’)
What is polymorphism?
1. when an entity is appearing with the same name in
different forms, then that entity is said to exhibit
polymorphism
2. method over riding is an example of polymorphism.

Does python support method overloading?


No

Can we achieve method overloading in python?


Yes, by using * parameter we can achieve method overloading
indirectly
what is the use of self keyword
1. self keyword refers to current instance or
current object.
2. by using self keyword we can create and
access instance variables

class Doctor:
def __init__(self,name,exp):
self.name = name
self.exp = exp
what is the use of super() function
by using super() function we can access parent
class methods from child class.

class A:
def m5(self):
print('hello')

class B(A):
def m6(self):
super().m5()
What is class variable?
1. If we declare a variable at class level, then it is
considered as a class variable.
2. we can use class name to access class variables.

class C:
x = 10
def display(self):
print('hello')

print(C.x)
What is the dif between instance variable and class variable?
Instance variable Class variable

Instance variables are object specific class variables are class specific

instance variables are declared with class variables are declared at the class
self keyword as prefix. level, without self keyword.
for accessing instance variables we for accessing class variables we can use
need to use object. class name.

class D:
x = 10
def __init__(self):
self.y = 20

d1 = D()
print(d1.y)
print(D.x)
What is the dif between instance method and class
method?
Instance method Class method

instance methods will have self Class methods will have cls parameter by
parameter by default. default.
Class method should be marked with
@classmethod decorator above the
method name.
For calling instance methods we need to For calling class methods we can use class
use object. name.

class E:
def m7(self): e1 = E()
print('instance method') e1.m7()
E.m8()
@classmethod
def m8(cls):
print('class method')
What is dif between static method and class method?
Static method Class method

If we use @staticmethod decorator If we use @classmethod decorator


above a method name, then that above a method name, then that
method is considered as static method is considered as static method.
method.
for calling static methods we can use For calling class methods we can use
class name. class name.
Static methods will not have any Class methods will have cls parameter
parameters by default. by default.

class F:
@classmethod
def m9(cls):
print('class method')
@staticmethod
def m10():
print('static method')
What is the parent most class for all classes?
object class
How will you access, members of other modules?
By using import keyword we can import one module into
other module and access its members.

What all the access specifiers supported in python?


1. Python explicitly doesn’t have any access specifiers.
2. But we can prefix a variable with 2 underscores or 1
underscore to mark it as private or protected respectively.

How will you create public variable in python?


1. public keyword is not available in python.
2. by default all the variables, methods, and classes are
considered public in python, which we can access from
any where.
How will you create private variable in python?
1. If we use 2 underscores before a variable or
method, then it is considered as private
member of that class.
2. we can access that member only with in the
same class.

class G:
def __init__(self):
self.__x = 10 #private variable x
def m11(self):
print(self.__x) #we can access same class

g1 = G()
print(g1.__x) #error we can’t access private variable outside class
How will you create protected variable in
python?
1. If we use 1 underscore before a variable or
method, then it is considered as protected
member.
2. Protected members can be accessible only
with in the same class, as well as in the child
class.
eg: _y = 20 #here y is considered as protected

How to create a default variable in python?


It is not possible.
What is an abstract method
1. by specifying @abstractmethod decorator above
the method name, we can mark a method as
abstract method.
2. generally abstract methods will not have method bodies.

eg:

@abstractmethod
def fun(self):
pass
what is an abstract class?
1. if a class contains one or more abstract methods then
it is called as abstract class.
2. an abstract class must inherit from predefined class
ABC.
3. we can’t create object for an abstract class.

eg:
from abc import ABC

class H(ABC):
@abstractmethod
def f1(self):
pass
when to use abstract method?
If you know only method name but you don’t know
the logic, then we make that method as abstract
method.
can we create object for an abstract class?
no
how do you use an abstract class?
we use an abstract class by inheriting into another
class, and by over riding all abstract methods of
parent class in the child class.
does python support multiple inheritance of
classes?
yes
what is is ABC?
1. ABC stands for abstract base class.
2. ABC is a predefined class of python. we need
to inherit from ABC class, to mark a class as
an abstract class.
what is abc?
1. It is a predefined module in python which
contains ABC class.
2. we need to import abc module to use ABC
class.
What is abstraction?
hiding implementation details and exposing the
required details to the user, is known as abstraction.

eg :

mobile phone is an example for abstraction.


because we don’t know the internal working mechanism of
mobile phone.
what is an exception?
exception is a run time error which terminates the
program abruptly.
how do you handle exceptions?
we will handle exceptions by using try-except blocks

try:
#code that gives error
except errorname:
#error storing code

Can we have multiple except blocks for one try block?


Yes, one try block can be followed by multiple catch
blocks.
What is finally block?
1. finally block code will be executed in all the
scenarios no matter whether exception occur or
does not occur.
2. finally block is used to clean important system
resources , like closing files, closing database
connections etc.

One try block can have how many finally blocks?


one try block can have maximum one finally block
Is it possible to have a try block without except
block?
yes we can have try without except block, in case if
finally block is available.
write one example for exception handling?

try:
x = [10,20,30]
print(x[3])
except IndexError:
print('trying to access invalid position')

You might also like