Top 56 Python Interview Questions & Answers

  • By
  • June 12, 2019
  • Python
Top 56 Python Interview Questions & Answers

Python Interview Questions

1.Tell me the difference between list and tuples in Python?

Ans:  Lists are mutable. Means we can add and remove elements in list.

Tuples are immutable Means we can add and remove elements in tuple.

Lists are slower than tuples.

Tuples are faster than list.

Syntax:

1 = [10, ‘Ch’, 20.7898]

Syntax:

t = (10, ‘Ch’ , 20.78)

2.How is python dynamically typed?

Ans: Python is dynamically typed, this means that you don’t need to specify the types of variables when you declare them.

3.What is pep 8?

Ans: PEP stands for Python Enhancement Proposal. It is a set of predefined rules that specify how the python code should be written for maximum readability.

  1. Explain memory managed in Python?

Ans: Python private heap space is used for memory management in python. All objects in Python and data structures are located in a private heap.The programmer does not have access to  private heap.For the allocation of heap space, Python objects are used by Python’s memory manager.Python also have garbage collector, which is responsible to delete all the unused memory and so that it can be made available to the heap space.

  1. What is PYTHONPATH?

Ans: PYTHONPATH is an environment variable which is used when a module is imported.

When a module is imported, PYTHONPATH is used to locate and load the module into our program.

PYTHONPATH is used to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load.

  1. Explain local and global variables in Python?

Ans: Global Variables:

Variables declared used a function or in global space are called global variables.

Local Variables:

Any variable used inside a function is known as a local variable. This is present in the local space and not in the global space.

Example:

m=2                       #Global Variable

def add():

n=3                       #Local Variable

s=m+n

print(s)

add()

Output: 5

When you try to access the local variable outside the function add(), it will throw an error.

  1. Why indentation is required in python?

Ans: Indentation is necessary for Python. It is used to specify a block of code. The scope of of loop is decided using indentation.

All code within loops, classes, functions, etc should be specified using an indented block. It is usually done using four space characters or a single tab.

If your code is not indented properly, it will throw error.

  1. What is the difference between Arrays in Python  and lists?

Ans: Arrays and lists, in Python, stores data in same way. But, arrays can hold data of single datatype only. whereas lists can hold data of any datatype.

List datatype is available by default in python, thus we don’t need to import any module.

But to create arrays in python we must import array module first.

  1. What are functions in Python?

Ans: A function is a block of code which is defined to perform a well defined and specific task. Function is executed only when it is called.

To define  function in python, the def keyword is used.

Example:

def disp():

   print(“Hi, everyone..”)

disp() #calling the function

Output: Hi, everyone

  1. What is __init__?

__init__ is a special method or constructor in Python.

This method special because it is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__ method.

  1. What is a lambda function?

Ans: lambda is an anonymous function(a function which does not have any name) is known as a lambda function.

This function accepts any number of parameters but, can have just one statement or expression..

For Free Demo classes Call: 8149467521

Registration Link: Click Here!

  1. What is self in Python?

Ans: Self is a special predefined variable in python. It holds the address of an instance or an object of a class which is currently in execution.

In Python, this is explicitly included as the first of each instance method.

The self variable in the init method refers to the newly created object while in other methods, it refers to the object whose method was called.

  1. Explain working of break, continue and pass?

Ans: Break: Breaks the flow of execution, and takes the control out of the loop.Condition must be specified for loop termination. when condition is met and break is executed control is transferred to the next statement.

Continue: Used to start the execution of loop. It is used to skip some part of a loop. once specified condition is met the control will be transferred to the beginning of the loop

Pass: Used when you need some block of code syntactically, but you want to skip its execution. This is basically a null operation.

     Nothing happens when this is executed

  1. How can we reverse a string without using function?

[::-1] is used to reverse the string.

For example:

s=”Hello”

rev=s[::-1]

print(rev)

What is the difference between range & xrange?

Q-xrange and range are same in terms of functionality. They are used to generate a list of integers.

Ans: The  difference is range returns a Python list object and x range returns an xrange object.

  1. How to write comments in Python?

Ans: There are two types of comments in python namely single line and multi line.

For single “#” is used. Each line that we want to comment should start with “#”.

For multi line comment either enclose the text in ”’…”’ or “””….”””.

  1. How can you capitalize the first letter of string?

Ans: For this we have capitalize() method. It capitalizes the first letter of a string. If the string already consists of a capital letter at the beginning,

then original string is returned.

  1. How will you convert a string to lowercase?

Ans:  To convert a string to lowercase, lower() function is used.

s=’ABC’

print(s.lower())

Output: abc

19.How to comment multiple lines in python?

Ans: Multi-line comments means commenting more than one line. All the lines to be commented should be prefixed by a #.

You can use shortcut method to comment multiple lines. Just select line that you want to comment, hold the ctrl key and left click.

This will comment all the lines of selected text.

  1. What are docstrings in Python?

Ans: Docstrings are are documentation strings. These docstrings are specified within triple quotes.

They are not assigned to any variable and thus, we can use them as comments as well.

  1. What are  is, not and in operators in Python?

Ans: Operators are special functions. They accept one or more values and produce the result.

is: returns true if both operands are true

not: returns the inverse of the boolean value

in: checks if element is present in specified sequence

  1. What is a dictionary in Python?

Ans: Dictionary is built-in datatypes in Python. It defines one-to-one relationship between keys and values. Dictionaries contain pair of keys and

their corresponding values. Dictionaries are indexed by keys.

  1. How  the ternary operators are used in python?

Ans: Ternary operator is the operator used to show the conditional statements. It consists of the true or false values with a statement that has to be evaluated for it.

Syntax:

[on_true] if [expression] else [on_false]

  1. What is len()?

Ans: len() is a function, which is used to determine the length of a string, a list, an array, etc.

Example:

s=’AB’

print(len(s))

  1. Explain negative indexes in Python

Ans: Sequences in Python are indexed, it has positive as well as negative index.

Positive index starts with ‘0’ as first index and ‘1’ as second index and the process goes on like that.

The other index which starts from ‘-1’ which represents the last index in the sequence and the sequence carries forward like the positive number.

For Free Demo classes Call: 8149467521

Registration Link: Click Here!

  1. What are Python packages?

Ans: Python packages are namespaces. It contains multiple modules in it.

  1. How can files be deleted in Python?

Ans: To delete a file in Python,  use the os.remove() function.

To use this first we need to import the OS Module.  

  1. What are the built-in types of python?

Ans: Built-in types in Python are as follows –

Integers

Floating-point

Complex numbers

Strings

Boolean

Built-in functions

  1. How to add values in python array?

Ans: To add elements to an array an use  append(), extend() and the insert (i,x) functions.

Example:

import array as ar

a=ar.array(‘d’, [1.1 , 2.1 ,3.1] )

a.append(3.4)

print(a)

a.extend([4.5,6.3])

print(a)

a.insert(2,3.34)

print(a)

  1. How can we remove values from  array?

Ans: Elements in Array can be removed using pop() or remove().

import array as arr

a=arr.array(‘d’, [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6])

print(a.pop())

print(a.pop(3))

a.remove(1.1)

31.Does Python have OOps concepts?

Ans: Python is an object-oriented programming language. Means that any program can be written in python by using class and object.

However, Python can be treated as procedural as well as structural language also.

  1. What is split?

Ans: split() is a function. split()  is used to separate a given string in Python.

Example:

a=”hello python”

print(a.split())

Output:  [‘hello’, ‘python’]

  1. Specify the  different ways of importing module in python?

Ans: Modules can be imported using the import keyword, in three ways-

import array           #importing using the original module name

import array as arr    # importing using an alias name

from array import *    #imports everything present in the array module

  1. Explain Inheritance in Python with their.

Ans: Inheritance allows One class to gain all attributes and methods of another class. Inheritance provides code reusability. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.

  1. Different types of inheritance supported by Python are as below:

Ans: Single Inheritance – where a single derived class acquires the members of a single super class.

Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 are inherited from d2.

Hierarchical inheritance – In this we define many child class using a single base class.

Multiple inheritance – In this weine single child class from more than one base class.

  1. How are classes created in Python?

Ans: To define class in Python is created using the class keyword.

class Emp:

   def __init__(self, name):

       self.name = name

E1=Employee(“abc”)

print(E1.name)

For Free Demo classes Call: 8149467521

Registration Link: Click Here!

  1. Does python support multiple inheritance?

Ans: Multiple inheritance means that a class can be derived from more than one parent classes. Python does support multiple inheritance.

  1. What is Polymorphism in Python?

Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism.

  1. Define encapsulation in Python?

Ans: Encapsulation means binding the code and the data together. A Python class in an example of encapsulation.

  1. How do you do data abstraction in Python?

Ans: Data Abstraction is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using interfaces and abstract classes.

  1. Does python make use of access specifiers?

Ans: Python does not deprive access to an instance variable or function. Python lays down the concept of prefixing the name of the variable, function or method with a single or double underscore to imitate the behavior of protected and private access specifiers.

  1. What is the output of:

Ans: lst1=[12,34]

lst2=[‘Hello’,35]

print(lst1 + lst2)

Output is: [12,34,’Hello’,35]

  1. Explain can we generate random numbers in Python?

Ans: To generate random numbers in Python,we need to import module random

import random

random.random()

This will return a random floating point number in the range [0,1)

  1. How can we  Randomize The Items Of A List In-Place?

Ans: Python has a built-in module called as <random>. It exports a public method <shuffle(<list>)> which can randomize any input sequence.

import random

list = [2, 18, 8, 4]

print(“Before Shuffling – 0”, list)

random.shuffle(list)

print(“After Shuffling – 1”, list)

random.shuffle(list)

print(“After Shuffling – 2”, list)

  1. What Is The Best Way To Split A String In Python?

Ans: We can use Python <split()> function to break a string into sub strings based on the defined separator. It will return the list of all words present in the input string.

test = “I am learning Python.”

print test.split(” “)

Program Output

[‘I’, ‘am’, ‘learning’, ‘Python.’]

  1. What Is The Right Way To Transform A Python String Into A List?

Ans: In Python, strings are just like lists. And it is easy to convert a string into the list. Simply by passing the string as an argument to the list would result in a string-to-list conversion.

list(“I am learning.”)

Program Output.

[‘I’, ‘ ‘, ‘a’, ‘m’, ‘ ‘, ‘l’, ‘e’, ‘a’, ‘r’, ‘n’, ‘i’, ‘n’, ‘g’, ‘.’]

  1. How Does Exception Handling In Python Differ From Java? Also, List The Optional Clauses For A <Try-Except> Block In Python?

Ans: Python implements exception handling indifferent way. It provides an option of using a <try-except> block where the programmer can see the error details without terminating the program. Sometimes, along with the problem, this <try-except> statement offers a solution to deal with the error.

There are following clauses available in Python language.

  1. try-except-finally
  2. try-except-else
  1.  What Do You Know About The <List> And <Dict> Comprehensions?

Ans: The <List/Dict> comprehensions provide an easier way to create the corresponding object using the existing iterable. The list comprehensions are usually faster than the standard loops. But it’s something that may change between releases.

  1. What Are The Methods  To Copy An Object In Python?

Ans: Commonly, we use <copy.copy()> or <copy.deepcopy()> to perform copy operation on objects. Though not all objects support these methods but most do.

But some objects are easier to copy. Like the dictionary objects provide a <copy()> method.

  1. Can You Write Code To Determine The Name Of An Object In Python?

Ans: No objects in Python have any associated names. So there is no way of getting the one for an object. The assignment is only the means of binding a name to the value. The name then can only refer to access the value. The most we can do is to find the reference name of the object.

  1. What is Python?

Ans: Python is a high-level language. It is also interpreted and object-oriented scripting language. Python is highly readable. It uses English keywords. Using python we can write procedural as well as object oriented programs.

  1. What is map function in Python?

Ans: map() executes the function given as the first argument on all the elements of the iterable given as the second argument. When function given takes in more than 1 arguments, then many iterables are given.

53 . How can we display the contents of text file in reverse order?

Ans: convert the given file into a list.

reverse the list using reversed()

Eg: for line in reversed(list(open(“file-name”,”r”))):

      print(line)

  1. Can we use duplicate kays in dictionary?

Ans: No, duplicate keys are not in  dictionary.

  1. Can we use duplicate values in dictionary?

Ans: Yes. We can have duplicate values in a dictionary.

  1. Which of the following is an invalid statement?

Ans: 

a) ab = 1,000,000

b) a b = 1000 2000

c) a,b,c = 1000, 2000, 3000

d) a_b_c_d = 1,000,000

Answer: b

For Free Demo classes Call: 8149467521

Registration Link: Click Here!

Call the Trainer and Book your free demo Class for now!!!

call icon

© Copyright 2019 | Sevenmentor Pvt Ltd.

Submit Comment

Your email address will not be published. Required fields are marked *

*
*