Credo Systemz

PYTHON INTERVIEW QUESTIONS AND ANSWERS


Python is one of the most marketable and in-demand programming languages. It is a versatile and easiest programming languages to learn. Python is used in all the trending technologies in the field of software development, such as Machine Learning, Data Science, AI, Web Development, and much more.

The aim of this blog is to expertise in python programming language and to practice for career development. We have 100+ Python Interview Questions and Answers prepared by python professionals. It is suitable for all aspirants to improve their technical skills. Every year new set of Python questions are updated along with placement assistance.

Python Interview Questions and Answers For Intermediate

Firstly, Python is the top general purpose programming languages with huge demand and library support. Due to its powerful libraries, Python is used in various domains, complex problems and powerful computations.

Python Interview Questions and Answers for Intermediate article helps to support intermediate python developers to practice and update themselves. Learn Python course in Chennai using practical training, placement support and professional trainer guidance.

Q1. How the string does get converted to a number?

To convert the string into a number the built-in functions are used like int() constructor. int() is a data type that is used like int (‘1’) ==1. float() is also used to show the number in the format as float(‘1’)=1.

In this the int(string, base) function takes the parameter to convert string to number in this the process will be like int(‘0x1’,16)==16. If the base parameter is defined as 0 then it is indicated by octal and 0x indicates it as a hexadecimal number. eval() is used to convert a string into number



Q2. What is a lambda function? How are these written in Python?

A lambda function is the anonymous function that can have any number of parameters but can have just one statement.

Example :
								
v = lambda p,q : p+q
print(v(6, 5))
	
Output: 12


Q3. How to reverse lists in Python using slicing?

[::-1] is used to reverse the order of an array or a sequence.


								
import array as arr
a=arr.array('i',[1,2,3,4])
a[::-1]			
							
Output:
array(‘i’, [4, 3, 2, 1])

[::-1] reprints the array as a reversed copy of ordered data structures such as an array or a list. The original array or list remains unchanged.

							
l = [ 'a','b','c','d' ]
l[::-1]

Output :
[ ‘d’, ‘c’, ‘b’, ‘a’ ]


Q4. What is the function of the negative index?

The sequences in python are indexed and it consists of positive as well as negative numbers. The numbers that are positive use ‘0’ that is uses as first index and ‘1’ as the second index and the process goes on like that.

The index for the negative number starts from ‘-1’ which represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number. The negative index is used to

  • To remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1].
  • To show the index to represent the string in the correct order.


Q5. How can one create classes in Python?

To create a class in Python, we use the keyword "class", as shown in the example below:
							
class Employee:
   def __init__(self, employee_name):
       self.name = employee_name


To instantiate or create the object from the class created above, we do the following:
 employee = Employee("John")

To access the name attribute, we call the attribute using the dot operator as shown below:
							
print(employee.name)
# Prints -> John


Take a look here :

Python is able to check multiple conditions at the same time which does not have to follow a particular order of operators.

Q6. How are access specifiers used in Python?

Python does not use access specifiers precisely like private, public, protected, etc. However. It has the concept of imitating variables' behavior using a single (protected) or double underscore (private) as prefixed to variable names. By default, variables without prefixed underscores are public.

							
# to demonstrate access specifiers
class Employee:
   
    # protected members
    _name = None
    _age = None
    
    # private members
    __department = None
    
    # constructor
    def __init__(self, emp_name, age, department): 
         self._name = emp_name
         self._age = age
         self.__department = department
    
    # public member
    def display():
        print(self._name + " "+ self._age + " " + self.__department)							
											


Q7. How can parent members be accessed inside a child class?

By using the name of the Parent class: use name of the parent class to access attributes as shown in the example below:

							
class Parent(object):  

   # Constructor

   def __init__(self, name):
       self.name = name    

 class Child(Parent): 

   # Constructor

   def __init__(self, name, age):

       Parent.name = name
       self.age = age

  def display(self)
  
       print(Parent.name, self.age)

 # Driver Code

obj = Child("ChildClassInstance", 9)
obj.display()




Q8. How does global value mutation used for thread-safety?

The global interpreter lock is used to allow the running of the thread one at a time. This is internal to the program only and used to distribute the functionality along all the virtual machines that are used. Python allows the switching between the threads to be performed by using the byte code instructions that are used to provide platform-independence.

The sys.setcheckinterval() method is used that allow the switching to occur during the implementation of the program and the instruction. This provides the understanding in the field of accounting to use the byte code implementation that makes it portable to use.



Q9. What is the 'main' function in Python? How do you invoke it?

The 'main' function is considered as an entry point for the execution for a program. But in Python, this is known that the interpreter serially interprets the file line-by-line. This means that Python does not provide the 'main()' function explicitly. But this doesn't mean that it a cannot simulate the execution of 'main'.

It can do this by defining the user-defined 'main()' function and using the python file's '__name__' property. This '__name__' variable is a particular built-in variable that points to the current module's name. This can be done as shown below:

							
 print("Hi!")
if __name__ == "__main__":
 main()


Output : Hi!


Q10. Write a program to read and write the binary data using python?

The module that is used to write and read the binary data is known as struct. This module allows the functionality and with it many functionalities to be used that consists of the string class. This class contains the binary data that is in the form of numbers that gets converted in python objects for use and vice versa. The program can read or write the binary data is:

							
 import struct
f = open(file-name, "rb")
# This Open() method allows the file to get opened in binary mode to make it portable for # use.
s = f.read(8)
x, y, z = struct.unpack(">hhl", s)

The ‘>” is used to show the format string that allows the string to be converted in big-endian data form. For homogenous list of data the array module can be used that will allow the data to be kept more organized fashion.



Did you know :

Unlike Java and C++, Python does not use braces but Indentation is mandatory.

Q11. Explain the use of subn(), sub(), and split() in the “re” module.

Re is a Python module developers use to execute operations that involve expression matching. In particular, it contains three modules to allow editing strings – subn(), sub(), and split().

Here are the differences between these methods:

Method nameApplication
subn()Defines all strings with a matching regex pattern, replaces them with a new one, and returns the number of replacements.
sub()Defines all strings with a matching regex pattern and replaces them with a new one.
split()Splits strings into lists using regex patterns
Items in list can be replaced or changed Items in set cannot be changed or replaced


Q12. How does Python approach multithreading?

Python has the following multi-threading tools:

  • A designated multi-threading package. It’s not widely used as it slows code execution down.
  • GIL (Global Interpreter Lock) constructor. It helps ensure that only one string is executed at a time. After GIL executes a string, it’ll get passed over to the next one.


Q13. What is inheritance? Name the main types of Python inheritance.

Inheritance is a way for a class to pass its members (e.g. methods or attributes) to a new class. In this case, a class that contains the original data is called a super-class. The inheriting class is called a child or derived class.

There are four inheritance types in Python:

  • Single inheritance – a child class inherits the data passed down by one super-class.
  • Multiple inheritance – a child class inherits the members of several super-classes.
  • Multi-level inheritance – a derived class d1 inherits the members of a super-class b1; a child class d2 inherits the data from a base class b2.
  • Hierarchical inheritance – a high number of child classes can inherit the members of one superclass.


Q14. Are there any tools for identifying bugs and performing static analysis in Python?

Yes, tools like PyChecker and Pylint are used as a static analysis and linting tools, respectively. PyChecker helps find bugs in a python source code file and raises alerts for code issues and complexity. Pylint checks for a module's coding standards and supports different plugins to enable custom features to meet this requirement.



Q15. What are Python packages?

Python packages are namespaces containing multiple modules such as “os”, “sys”, “json”, “pandas” etc.



Make a Note :

As a Python Variables, it can can only begin with a letter(A-Z/a-z) or an underscore(_).

Q16. How can you randomise the items of a list in place in Python?

from random import shuffle

Output :
['sentence', 'This', 'will', 'shuffled', 'be', 'now']

Every time output can be random.



Q17. what is the difference between range & ‘xrange’?

'xrange' and 'range' provide a way to generate a list of integers to use. The only difference is that 'range' returns a Python list object while 'xrange' returns an 'xrange' object. 'xrange' doesn't generate a static list at run-time as 'range' does. It creates the values as you need them with a unique technique called yielding.

This technique is used with a type of object known as generators. That means that if you have a vast range, you'd like to generate a list for, say, one billion, 'xrange' is the function to use.



Q18. What are modules and packages in Python?

Modules are simply Python files with a '.py' extension and can have a set of functions, classes and variables defined. They can be imported and initialised using import statements if partial functionality is required to import the requisite classes or processes.

Packages provide for hierarchical structuring of the module namespace using a '.' dot notation. As modules help avoid clashes between global and local variable names, similarly, packages can help prevent conflicts between module names. Creating a package is easy since it also uses the system's inherent file structure that exists.

Modules combined into a folder are known as packages. Importing a module or its contents from a package requires the package name as a prefix to the module's name joined by a dot.



Q19. What does '*args' and '**kwargs' stand for in Python?

*args is a particular parameter used in the function definition to pass arguments with a variable number of items. "*" means variable length, and "args" is a name used as a convention.

**kwargs is a special syntax used as the function definition to pass a variable-length keyword argument. It can be used just as a convention. It can also use any other name to represent "kwargs" here.



Q20. Is it possible to call parent class without its instance creation?

Yes, it is possible if other child classes instantiate the base class or if the base class is a static method.





Conclusion:

As a python aspirants practice more, learn new frameworks and update yourself to move forward. Credo Systemz make way for upliftment using Python training course in Chennai. Feel free to contact the technical team for more Python programming interview Questions and Answers and career guidance.

Python Interview Questions and Answers for Freshers

To begin, Python is one of the most widely-used programming languages. It is free and open-source language providing flexibility using dynamic semantics. Python is also a very simple and easy to learn language.

In recent times, Python is used in all the trending technologies like Machine Learning, Artificial Intelligence, Web Development, Web Scraping, and various other domains powerful libraries.

In this article, we will see the Python Interview Questions and Answers which will help you excel and practices for performing well in job interviews.

Q1. When do you use list vs. Tuple vs. Dictionary vs. Set?

List and Tuple are both ordered containers. If you want an ordered container of constant elements use tuple as tuples are immutable objects and list are mutable in nature.



Q2. Explain all the file processing modes supported by Python?

Python allows to open files in one of the three modes. They are:
  • read-only mode
  • write-only mode
  • read-write mode
  • Append mode
  • By specifying the flags “r”, “w”, “rw”, “a” respectively.

  • A text file can be opened in any one of the above said modes by specifying the option “t” along with “r”, “w”, “rw”, and “a”, so that the preceding modes become “rt”, “wt”, “rwt”, and “at”.

  • A binary file can be opened in any one of the above said modes by specifying the option “b” along with “r”, “w”, “rw”, and “a” so that the preceding modes become “rb”, “wb”, “rwb”, “ab”.


Q3. When does a dictionary is used instead of a list?

  • Dictionaries :are best suited when the data is labeled, i.e., the data is a record with field names.
  • Lists are a better option to store collections of un-labeled items say all the files and subdirectories in a folder. List comprehension is used to construct lists in a natural way. Generally, the Search operation on a dictionary object is faster than searching a list object.


Q4. Differentiate between append() and extend() methods ?

Both append() and extend() methods are the methods of the list. These methods are used to add the elements at the end of the list.

  • append(element) – adds the given element at the end of the list which has called this method.

  • extend(another-list) – adds the elements of another list at the end of the list which is called the extend method.



Q5. Is all the memory freed when Python exits?

No, it is not, because the objects that are referenced from global namespaces of Python modules are not always deallocated when Python exits.



Check this out :

With slicing, it is easier to reverse a list from starting to end but with a step of --1.

Q6. Difference between str() and repr()?

repr() compute the “official” string representation of an object i.e. a representation that has all information about the object and str() is used to compute the “informal” string representation of an object (a representation that is useful for printing the object)



Q7. What are higher-order functions?

A function is called Higher Order Function if it contains other functions as a parameter or returns a function as an output i.e., the functions that operate with another function are known as Higher-order Functions.



Q8. How to copy objects in python?

Use = operator to create a copy of an object. It creates a new variable that shares the reference of the original object.



Q9. How to make an array in python?

Array in Python can be created by importing an array module. array(data_type, value_list) is used to create an array with data type and value list specified in its arguments.



Q10. How to handle exceptions?

Exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can then choose what operations to perform once we have caught the exception.



Think about that for a min :

In Python, you can declare a local variable in a function, class, or so which will be only visible in that scope. If you call it outside of that scope, then you get an ‘undefined’ error.

Q11. What are a static method, class method, and instance method?

Instance methods need a class instance and can access the instance through self. Class methods don't need a class instance. They can't access the instance ( self ) but they have access to the class itself via cls. Static methods don't have access to cls or self.



Q12. What are iterators and generators?

An iterator in python is an object that is used to iterate over iterable objects like lists, tuples, dicts, and sets. The iterator object is initialized using the iter() method. It uses the next() method for iteration. Generators in Python are used to create iterators and return a traversal object. It helps in traversing all the items one at a time with the help of the keyword yield.



Q13. What are exec() and eval () in python ?

The exec() function executes the specified Python code. The exec() function accepts large blocks of code, unlike the eval() function which only accepts a single expression.



Q14. What is a descriptor?

Python descriptors are a way to create managed attributes. Among their many advantages, managed attributes are used to protect an attribute from changes or to automatically update the values of a dependant attribute. Descriptors increase an understanding of Python and improve coding skills.



Q15. What is MRO?

Method Resolution Order (MRO) denotes the way a programming language resolves a method or attribute. Python supports classes inheriting from other classes. The class being inherited is called the Parent or Superclass, while the class that inherits is called the Child or Subclass.



know the best part :

Python is one of the official Google languages due of its efficiency. It is advantageous with simple to use, even on large projects. YouTube is also powered by Python programming.

Q16. What are Metaclasses?

A metaclass in Python is a class of a class that defines how a class behaves. A class is itself an instance of a metaclass. A class in Python defines how the instance of the class will behave. In order to understand metaclasses well, one needs to have prior experience working with Python classes.



Q17. Differentiate mutable vs immutable :

MutableImmutable
The objects can be modified after the creation as well.Objects cannot be modified after the creation of the objects.
Objects cannot be modified after the creation of the objects.Classes that are immutable are considered final.Thread-safe.
Classes are not made final for the mutable objects.Classes are made final for the immutable objects
Example: Lists, Dicts, Sets, User-Defined Classes, Dictionaries, etc.Example: int, float, bool, string, Unicode, tuple, Numbers, etc.


Q18. Differentiate between list and Python array?

ListTuples
consist of elements belonging to different data typesOnly consists of elements belonging to the same data type
No need to explicitly import a module for declarationNeed to explicitly import a module for declaration
Cannot directly handle arithmetic operationsCan directly handle arithmetic operations
Can be nested to contain different type of elementsMust contain either all nested elements of same size
Preferred for shorter sequence of data itemsPreferred for longer sequence of data items


Q19. What are the methods of dict?

MethodDescription
clear()Removes all the elements from the dictionary
copy()Returns a copy of the dictionary
fromkeys()Returns a dictionary with the specified keys and value
get()Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys


Q20. What is negative index in Python?

Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth.



Learn here :

Function Argument Unpacking is another awesome feature of Python. Unpack a list or a dictionary as function arguments using * and ** respectively. This is commonly known as the Splat operator.

Q21. Mention what are the rules for local and global variables in Python?

  • Local variables : If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be local.

  • Global variables : Those variables that are only referenced inside a function are implicitly global.


Q22. How can you share global variables across modules?

To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.



Q23. Mention the benefits of using Python?

  • Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc.
  • Python does not require explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically.
  • Provides easy readability due to the use of square brackets.
  • Easy-to-learn for beginners.
  • Having the built-in data types saves programming time and effort from declaring variables.


Q24. How Python is interpreted?

Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.



Q25. What is Scope in Python?

A scope defines the hierarchical order in which the namespaces have to be searched in order to obtain the mappings of name-to-object(variables). It is a context in which variables exist and from which they are referenced. It defines the accessibility and the lifetime of a variable.



Small Stuff here :

In Python, you can declare a local variable in a function, class, or so which will be only visible in that scope. If you call it outside of that scope, then you get an ‘undefined’ error.

Q26. Explain isinstance()?

The isinstance() function returns True if the specified object is of the specified type, otherwise False. If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.



Q27. Differentiate between List, Set, and Tuple :


ListSetTuple
Lists is MutableSet is MutableTuple is Immutable
It is Ordered collection of itemsIt is Unordered collection of itemsIt is Ordered collection of items
Items in list can be replaced or changed Items in set cannot be changed or replacedItems in tuple cannot be changed or replaced


Q28. Explain the key features of python ?

Python is a dynamic, high-level, free open source, and interpreted programming language. It supports object-oriented programming as well as procedural-oriented programming. In Python, we don't need to declare the type of variable because it is a dynamically typed language.

Key Features of Python


Q29. Explain indexing and slicing?

Indexing refers to an element of an iterable by its position within the iterable. The slicing operation helps in getting a subset of elements from an iterable based on their indices.



Q30. Difference between str() and repr() ?

repr() compute the “official” string representation of an object (a representation that has all information about the object) and str() is used to compute the “informal” string representation of an object (a representation that is useful for printing the object).


Conclusion :

To finalize, learn Python Training in Chennai at Credo Systemz to develop the in-built knowledge with placement assistance. This Python Interview Questions and Answers for Freshers helps to strength the basic concepts of python and to practice them effectively.




Python OOPS Interview Questions And Answers

To start with, Python is the best programming languages. Python supports object oriented programming and used in all the trending technologies using powerful libraries. The demand for python developers increases globally with benefits like career growth, versatile fields, salary package and much more.

In this article, let’s see the Python OOPS Interview Questions and Answers to understand the python OOPS concepts to start the career with top job offers.

Q1. Write a code to show multiple inheritance in Python :

							
class Parent1:
def first_parent(self):
print(‘This is first parent class’)
class Parent2:
def second_parent(self):
print(‘This is second parent class’)
class ChildClass(Parent1, Parent2):
def child_class (slef):
print(‘This is child class’)
obj = ChildClass()
obj.first_parent()
obj.second_parent()
obj.child_class()



Q2. What is the use of super()?

super() is used as a temporary object of the parent class, in a child class. Using super(), the child class can refer to any method of the parent class.


Q3. What are new and override modifiers?

  • New Modifiers - state the compiler to run a new function and not use the one from the base class.
  • Override Modifier - instructs to run the base class version of a class and not create a new one. This reduces unnecessary repetitions of writing codes.


Q4. What are abstract methods?

Abstract methods are declarations of methods without proper implementation. The implementation is done when inherited into child classes and defined.



Q5. What is a Class variable?

Class variables are accessible in all instances of the class. In the python class, Class variables are defined at the beginning of the class. If a class variable changes in one instance, its effect is in the class variable of the other instance. We can access class variables outside the class also, to access it use the class name and class variable name.



You know this :

Python was initially released in 1991 whereas Java was released in 1995. Thus, Python is almost 30 years old and stands strong for the future.

Q6. What is new method in Python?

The new method creates the instance of a class. It will use to control the creation of a new instance of the class. It allocates memory for the object. The instance variables of an object need memory to hold it. This method will be called at the time of object creation. The new method accepts a type as the first argument and returns a new instance of that type. The new method will be used to control the creation of a new instance. The new method returns the new instance to called class.

							
class Student(): 
def __new__(cls): 
print("We are in new method") 
return super(Student, cls).__new__(cls) 

def __init__(self): 
print("We are in init method") 

student = Student() 
print(student)
)


Q7. What is the difference between new and init in python?


Initnew
init method is used to initialize the instance variables after the class instance created by a new method.new method creates the instance of a class. It uses to control the creation of a new instance.
init method initializes the variables of the object.new method allocates memory for the object. The instance variables of an object need memory to hold it.
init method will be called to initialize the objectnew method will be called when an object is created.
init accepts an instance as the first argument and sets the instance variables.new accepts a type as the first argument and returns a new instance of that type.
init method is suitable for mutable types.The new method is suitable for use with mutable and immutable types.


Q8. What are the different types of Methods in Python?

There are 3 different types of methods in the class. All the class activities are performed using all these methods.

  • Instance Methods
  • Class Methods



Q9. What is Inheritance in Python?

In inheritance, the new class is to be derived from the existing class. By inheritance, the variables and methods of the existing class are accessible in the new class. All classes in python are derived from the object class. When we create a Python class, internally the object class becomes the superclass. The main advantage of inheritance is code accessibility.

							
class Student(object)
  pass
  
class Student:
  pass



Q10. What is Constructor Overriding in Python?

If we write a constructor in both the classes then the child class can’t access the constructor of a parent class. In such a case only child class constructor is available i.e. child class constructor replaces parent class constructor. Constructor Overriding is used when the existing constructor has to be modified.

							
class University: 
  def __init__(self): 
    self.name = 'Yele University'
    print("You are in University Class Constructor")
 
class College (University):
  def __init__(self):
    self.name = 'Yale School of Medicine'
    print('You are in college Class Constructor')
 
  def show(self):
    print('College class instance method:',self.name)
 
college = College()
college.show()


Funny Fact :

Here is a fun fact, Python is an old programming language even older than Java.

Q11. What is Super Method in Python?

If we write a constructor in both the classes then the parent class constructor is not available in the child class. In such a case, the child class constructor replaces the parent class constructor. If we want to access the parent class constructor then we have to use the super method.



Q12. What is Polymorphism in Python?

The polymorphism, poly meaning many, and morphos meaning forms. If there is a different behavior according to a variable or method situation, then it is called Polymorphism. Given below are 3 different types of Polymorphism.

  • Duck Typing
  • Operator Overloading
  • Method Overriding


Q13. What is Strong Typing in Python?

When an object is passed in strong typing, then it is checked whether the method is present or not in that object. Using Python’s hasattr() function, you can check whether the method is present in the passed object.



Q14. hat is Method Overriding in Python?

If we write the same name method in child class and parent class then a method of parent class is not accessible in child class. In such a case, the method of the child class replaces the method of the parent class. Method overriding is used when we have to change the existing behavior of the program.



Q15. What is Interface in Python?

Python does not have an explicit interface concept like other languages such as Java. The interface in python is that there is only an abstract method in an abstract class and there is no concrete method.



Let's dig a little deeper :

Python programming language is high in demand with drastic growth in the past 10 years.

Q16. What is the difference between Abstract Class vs Interface?

An abstract class has abstract methods as well as concrete methods but all methods in an interface are abstract methods. We use abstract class when all the objects share common features whereas we use interface when all the features are implemented differently for different objects. It is the programmer’s responsibility to write a child class in an abstract class, while any third-party vendor can write a child class in the interface. The interface is slow as compared to an abstract class.



Q17. What is the difference between instance, class and static method in python?

Instance methodClass methodStatic method
Instance methods are the most common type of method in python classes.The class of the object instance is implicitly passed as the first argument instance of self.Neither self (object instance) nor cls(the class) is implicitly passed as the first argument.
The instance method takes self(instance details) as an argument.A class method is like an instance method in that it takes an implicit first argument as clsIt is like a module-level function. They behave like plain functions except that you can call them from an instance or the class.
Functions that have the first argument as a class name.
A function that has the first argument as self.Simple functions with no self/cls argument
Can be called through the class.Can be called through the class and instance method.Can be called through the class and instance method.


Q18. How to define Encapsulation in python?

Python has encapsulation which we use in class. There is no access control to access private and public attributes in a python class. Single and double underscores are used for naming conventions in python classes. The single underscore variable is called private and accessing it directly should be avoided. Double underscore attributes are also private, which python mangles to hide the attribute name.



Q19. What is a Enumerations in python?

The base class for enums is Enum. To create an enumeration we need to subclass it. Each member of an enumeration has a type of enumeration class itself. Enums are callables, and we can look up a member by value by calling the enumeration.



Q20. What is The __del__ Method in python?

The del method is called before the object is about to be garbage collected. This is sometimes called the finalizer. It is sometimes referred to as the destructor, but that’s not really accurate since that method does not destroy the object – that’s the Garbage Collector’s responsibility – del just gets called prior to the GC destroying the object.



Conclusion:

Python Is the popular programming language with huge benefits for all the aspirants in the IT field. Learn Python training and certification in Chennai using placement support using interview tips,Python Interview questions and Answers, job offers and much more.

Python Programming/ Coding Interview Questions

First of all, Python is one of the top programming languages with huge library support. It is free, interpreted language providing flexibility and easy to learn for developers. Python supports multiple programming paradigms like object-oriented programming used to perform general-purpose programming.

This article explains the Python Coding Interview Questions and Answers that helps to boost the coding skills of the aspirants. It explains the coding questions with answers asked in top MNCs. Python training course in Chennai assists in developing all the skills needed for the certified python professional. Global Companies are willing to offer amazing job roles and benefits to Python developers.

Q1. What do you mean by list comprehension?

The process of creating a list while performing some operation on the data so that it can be accessed using an iterator is referred to as List Comprehension.

Example:

[ord (j) for j in string.ascii_uppercase]
[65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]



Q2. How will you convert a string to an int in python?

Example :
								
a=('1')
b=2
c=int(a)+b
print c
	


Q3. How will you convert an integer to a character in python?

print chr(97) and print ord(‘a’) for character to integer.



Q4. How can you pick a random item from a list or tuple?

Using random keyword

							

import random
foo = ['a', 'b', 'c', 'd', 'e']
print (random.choice(foo))


Q5. How will you capitalizes the first letter of the string?

							
a='abc'
print a[0].upper()




In short note :

Python feature allows to return multiple values using function.

def fun():
x = 6
y=3
a=x+y
b=x-y
Return a, b;
a, b = fun()
print(a)
print(b)

Q6. How will you check in a string that all characters are in uppercase?

							
character=("india")
if (character == character.upper()):
print "uppercase"
else:
print "lowercase"
	


Q7. What is the difference between del() and remove() methods of list?

If you know the element you want to remove (but not the index), you can use remove: del removes a specific index: remove removes the first matching value, not a specific index:



Q8. Write a program which can compute the factorial of a given numbers.

							
from math import factorial
print factorial(8)
or
a=input("enter the input")
factorial=1
for i in range(1,a + 1):
factorial=factorial*i
print factorial




Q9.Write a program that accepts a sentence and calculate the number of letters and digits.

							
a=raw_input("enter the string : ")
letters=0
num=0
for x in a:
if x.isdigit():
num= num + 1
else:
letters=letters + 1
print "Letters:" ,letters
print "Digits :" ,num


Input : hello! 100
Output : LETTERS 5
DIGITS 3


Q10. Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.

							
a=raw_input("enter the number : ")
x1=a
x2=a+a
x3=a+a+a
x4=a+a+a+a
b=int(x1)+int(x2)+int(x3)+int(x4)
print b



Q11. Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers.

							
from math import factorial
c=[]
a=input("enter the number : ")
for i in a:
if i%2!=0:
b=i**2
c.append(b)
print c



Conclusion:

Finally, Python course in Chennai provide the best training and placement support using HR team. This Python Coding Interview Questions and Answers helps to review the coding skills of the aspirants and to grab the job offers.

Python Interview Questions and Answers for Experienced Professionals

Basically, Python is one of the popular, widely-used programming languages. It is interpreted, free and open-source top programming language. With very simple and clean syntax, Python is used to perform general-purpose programming using object-oriented support.

Due to its tremendous growth, Python is used in all the trending technologies with lot of career opportunities. Using powerful libraries, there is a huge demand for python developers globally. Let’s take a look at the Python Interview Questions And Answers for Experienced Professionals that helps to achieve the career growth.

Q1. How to remove spaces from a string in Python?

strip () or replace() functions can be used to remove spaces from a string in python. strip() is used to remove the leading and trailing white spaces while the replace() function is used to remove all the white spaces in the string:
Syntex :
							
string.replace(” “,””) 
Example 1:
			
str1= “greatlearning”
print (str.strip())	

Output : great learning

Example 2:
							
str2=”great learning”
print (str.replace(” “,””))	

Output :greatlearning


Q2. What is the < Yield > Keyword in Python?

The keyword functions like a standard return keyword. It turns the function into a generator. It always returns a generator object. A function can have multiple calls to the keyword.

Program:
							
def sample(index):
month = ['jan','feb','march','april','may','june','july','aug','sep','oct','nov','dec']
yield month[index]
yield month[index+1]
months = sample(1)
print (next(months), next(months))
Output :

feb march


Q3. How do you implement inheritance in Python?

The parent class can be passed to the child class as an argument. We can invoke the init method parent class in the child class.

Program:
				

class Base1(object):
def __init__(self):
self.str1 = "hi"
print("Base")        
class Derived(Base1): def __init__(self):
# Calling constructors of Base1 class
Base1.__init__(self) print("Derived") def printStrs(self): print(self.str1)
ob = Derived() ob.printStrs()

Output :

Base
Derived
hi



Q4. What are shallow and deep copy?

Shallow Copy : it creates the exact copy as the original without changing the references of the objects. Both copied and original objects refer to the same object references. So, changing one object will affect the other.The copy method from the copy module is used for the shallow copy.

Program :

						

from copy import copy
a = [1, [2, 3]]
b = copy(a)
a[1].append(4)
print(a)
print(b)


Output :
[1, [2, 3, 4]]
[1, [2, 3, 4]]

Deep Copy: it copies the values of the original object recursively into the new object. Use the slicing or deepcopy function from the copy module for the deep copying.

Program :

					

from copy import deepcopy
a = [1, [2, 3]]
b = deepcopy(a)
a[1].append(4)
print(‘a=’)
print(a)
print(‘b=’)
print(b)
b[1].append(5)
print(‘a=’)
print(a)
print(‘b=’)
print(b)
a=[1, [2, 3, 4]] b=[1, [2, 3]] a=[1, [2, 3, 4]] b=[1, [2, 3, 5]]


Q5. What is the difference between Python Arrays and lists?

Python Arrays and List are collections of elements that are ordered and mutable. The list is one of the in-built complex data type which can store heterogeneous data. Arrays can store

  • Heterogeneous data when imported from the array module.
  • Homogeneous data when imported from the NumPy module
But lists can store heterogeneous data, and to use lists, it doesn’t have to be imported from any module. Arrays have to be declared before using it but lists need not be declared. Numerical operations are easier to do on arrays as compared to lists.


Note it :

There are four numeric Python data types.

  • Int
  • Float
  • Long
  • complex

Q6. What is the difference between xrange and range in Python?

In python range() and xrange() are inbuilt functions used to generate integer numbers in the specified range. The difference between the range () and xrange() can be understood if python version 2.0 is used because the python version 3.0 xrange() function is re-implemented as the range() function itself. range() takes more memory and returns a list of integers. xrange(),execution speed is faster and returns a generator object.



Q7. Explain the file processing modes that Python supports.

File processing modes in Python:

  • read-only(r)
  • write-only(w)
  • read-write(rw)
  • append (a)
The preceding modes become “rt” for read-only, “wt” for write and so on. Binary file can be opened by specifying “b” along with the file accessing flags (“r”, “w”, “rw” and “a”) preceding it.

Q8. How can you find the minimum and maximum values present in a tuple?

  • min() function can be used on top of the tuple to find out the minimum value present in the tuple:

Program:

							
tup1=(2,3,4,5)
min(tup1)


Output :
2
The minimum value present in the tuple is 2.


  • max() function help to find out the maximum value present in the tuple:
Program:

							
tup1=(1,2,3,4)
max(tup1)
		

Output :
4
the maximum value present in the tuple is 4


Q9. If you have two sets like this -> s1 = {3,4,5,6}, s2 = {5,6,7,8,9}. How would you find the common elements in these sets?

The intersection() function can be used to find the common elements between the two sets:
s1 = {3,4,5,6}
s2 = {5,6,7,8,9}
s1.intersection(s2)
The common elements between the two sets are 5 & 6.



Q10. Print the following pattern

#
# #
# # #
# # # #
# # # # #

Program:

							
# outer loop represent the number of rows
# inner loop represent the number of columns 
# n is the number of rows. 
for i in range(0, n):
# value of j depends on i 
for j in range(0, i+1):
# printing hashes print("#",end="")
# ending line after each row print("\r") num = int(input("Enter the number of rows in pattern: ")) pattern_1(num)


You know this :

Delete Python variables using the keyword ‘del’.

>>> a='python'
>>> del a
>>> a

Q11. What is Tkinter?

Tkinter is a Python library that helps to craft a GUI. It provides support for different GUI tools and widgets like buttons, labels, text boxes, radio buttons, and more. These tools and widgets have attributes like dimensions, colors, fonts, colors, and more.
Import the tkinter module.

							
import tkinter
top = tkinter.Tk()
	

Q12. Explain garbage collection with Python.

Python maintains a count of how many references are there in each object in memory When a reference count drops to zero, it means the object is dead. The garbage collector looks for reference cycles and cleans them. Python uses heuristics to speed up garbage collection.



Q13. What are pickling and unpickling?

To create portable serialized representations of Python objects, we have the module ‘pickle’. It accepts a Python object and then converts it into a string representation. It uses the dump() function to dump it into a file. This is called pickling. In contrast, retrieving objects from this stored string representation is termed ‘unpickling’.



Q14. How do we make forms in Python?

The cgi module is used to make forms. We can borrow the FieldStorage class from it. It has the following attributes: form.name: Name of field.

  • form.filename: Client-side filename for FTP transactions.
  • form.value: Value of field as a string.
  • form.file: File object from which to read data.
  • form.type: Content type.
  • form.type_options: Options of ‘content-type’ line of HTTP request, returned as dictionary.
  • form.disposition: The field ‘content-disposition’.
  • form.disposition_options: Options for ‘content-disposition’.
  • form.headers: All HTTP headers are returned as a dictionary.


Q15. What are accessors, mutators, and @property?

Like getters and setters in Java, we use accessors and mutators in Python. We have @property, which is syntactic sugar for property(). This lets us get and set variables without compromising on the conventions.


Short note :

Assign values to multiple Python variables in one statement.

Eg:
name,city=’xyz’,'chennai'
print(age,city)

Q16. Does Python support interfaces as Java does?

No. But Abstract Base Classes (ABCs) are a feature from the abc module that let us declare what methods subclasses should implement.



Q17. If a function does not have a return statement, is it valid?

A function that doesn’t return anything returns a none object. return keyword ends the function wherever present in the function. Normally, a block of code marks a function, and where it ends, the function body ends.

Q18. Differentiate between the append() and extend() methods of a list.

The methods append() and extend() work on lists. While append() adds an element to the end of the list, extend adds another list to the end of a list.
Let’s take two lists.
							
list1,list2=[1,2,3],[5,6,7,8]

append() is used as:
							
list1.append(4)
list1	
[1, 2, 3, 4]

extend() is used as:
							
list1.extend(list2)
list1
[1, 2, 3, 4, 5, 6, 7, 8]

Q19. What does the map() function do?

map() executes the function we pass to it as the first argument; it does so on all elements of the iterable in the second argument.

							
for i in map(lambda i:i**3, (2,3,7)):
print(i)

Output :
8
27
343

This gives us the cubes of the values 2, 3, and 7.

Q20. Why are identifier names with a leading underscore disparaged?

Python does not have a concept of private variables, use leading underscores to declare a variable private.



Facts :

Python can implement the ‘else’ clause within ‘for’ loop.

for i in range(1,4): print(i)
else:
print(“Executed only if no break”)

Q21. How will you create the following pattern using Python?
*
**
***
****
*****
Use two for-loops for this.

							
for i in range(1,6):
for j in range(1,i+1):
print('*',end='')
print()


Q22. Is a NumPy array better than a list?

NumPy arrays have the following benefits over lists:


  • NumPy are faster
  • They require less memory
  • They are more convenient to work with


Q23. Are methods and constructors the same thing?

No, there is some considerable differences-

  • Name a constructor in the name of the class; a method name can be anything.
  • When we create an object, it executes a constructor; whenever we call a method, it executes a method.
  • For one object, a constructor executes only once; a method can execute any number of times for one object.
  • Use constructors to define and initialize non-static variables; Use methods to represent business logic to perform operations.


Q24.What are the file-related modules we have in Python?

o manipulate text and binary files on our file systems-
os
os.path
shutil



Q25. How would you make a Python script executable on Unix?

The conditions are:

  • The script file’s mode must be executable.
  • The first line must begin with a hash(#). An example of this will be: #!/usr/local/bin/python.


Look it :

Python is dynamically-typed, we can want convert a value into another type easily with list of functions.

For example:
int()-It converts the value into an int.
int(3.6)

Q26. Explain inheritance in Python?

When one class inherits from another, it is said to be the child/derived/subclass inheriting from the parent/base/super class. It inherits/gains all members like attributes and methods.



Q27. Mention the different types of inheritance supported by Python.

Python supports the following inheritances:

  • Single Inheritance- A class inherits from a single base class.
  • Multiple Inheritance- A class inherits from multiple base classes.
  • Multilevel Inheritance- A class inherits from a base class, which, in turn, inherits from another base class.
  • Hierarchical Inheritance- Multiple classes inherit from a single base class.
  • Hybrid Inheritance- Hybrid inheritance is a combination of two or more types of inheritance.


Q28. Explain lambda expressions?

When we want a function with a single expression, we can define it anonymously. A lambda expression may take input and returns a value.
lambda expression:

							
(lambda a,b:a if a>b else b)(3,3.5)


Q29. What is a generator?

Python generator produces a sequence of values to iterate on. This way, it is kind of an iterable. We define a function that ‘yields’ values one by one, and then use a for loop to iterate on it.


Q30. How do you reverse a list in Python?

To reverse a list in Python:


  • Use the reverse() method.
  • Use slice() method from right to left.

Conclusion:

To sum up, Python training course in Chennai at Credo Systemz provide effective training to develop the skill set and job support. This Python Interview Questions and Answers helps to achieve better understanding and improvement the career path.

All the best!


Related Search Tags