16 Python Intermediate Interview Questions & Answers
Below is a list of our Python Intermediate interview questions. Click on any interview question to view our answer advice and answer examples. You may view 5 answer examples before our paywall loads. Afterwards, you'll be asked to upgrade to view the rest of our answers.
1. What is the Docstrings?
This question to test the knowledge of writing clean python codes.
It is simply embedded documentation in the source code. Docstrings are not comments. Docstrings are intended to provide documentation for a particular component (a module, class, method, or function ) in the code that will be useful for other developers.
Here is an example of the Docstring.
def exampe():
""" This is how and where the Docstrings are written.
IT can be one line or multiple.
"""
pass
It must start and end with a Three double quotation mark (""" Docstring """). Between them, You can write many lines to explain and describe your function, class, method or module.
The docstring is not something separated or isolated from the code. It becomes part of the code, and you can access it. It can be returned by the __doc__ method. It is a built-in method. Here is how to do it.
exampe.__doc__
The output is: 'This is how and where the Docstrings are written.\n IT can be one line or multiple.\n '
If the function does not have a docstring. The __doc__ will return nothing.
They are very important to write clean and good code. If you think
about it, the reason for documentation is because it
is intended to be read by other humans.
This question can be asked in other ways such as " How can you write an embedded documentation for a class or function?".
Written by Aiad Asaad on May 17th, 2021
2. What do you know about classes in python?
This question to test the ability of writing classes in python.
The class is a collection of methods with common objects. It is used in writing libraries and packages in python. It can organize and utilize the code blocks. For example, we can say that a circle is a class. It has some methods such as the area and the circumference. Those two methods have a common object which is the radius. However, the objects might not be common between methods.
To write a class in python you should use the Keyword class, followed by the class name, then a colon(:). After that, the first thing is the constructor. The main objective of a constructor is to initialize(assign values) data members of the class. In python, a class constructor is started by "def init(self, parameters of the class):". Here is an example of a simple class.
class circle:
def __init__(self,r):
self.r=r
def area(self):
return 3.14*self.r*self.r
After writing class, As in function to use it, you should call it with its parameters.
C=circle(13)
After calling it, Now we can get the area of the circle by this code.
Area=C.area()
print(Area)
You will get the area of the circle with a radius of 13.
Written by Aiad Asaad on May 17th, 2021
3. What is the optional argument?
This is a technical interview question to test the knowledge about the arguments.
when we speak about arguments, it means the parameters belong to a function, a class or a method.
There are two types of arguments.
1-Optional arguments.
2-Required argument.
The optional arguments are those that have an initial value. this means that, while creating the function, for example, those parameters are set with a value. Here is an example of that:
L=[1,2,3,4,5]
a=L.pop(0)
b=L.pop()
In the above code, we can see that the pop() method is used twice. One with a parameter and another without parameters. This means it has an optional parameter and is set to -1 to remove the last element. However, we can change it anytime with any possible index.
The required arguments are those without them the method can not be performed. This means you must enter them to execute the method. Here is an example:
L=[1,2,3,4,5]
L.remove()
If you run this, you will get an error as the method remove takes one required argument. Therefore you must run it with the element you want to remove. for example, L.remove(4), to remove element 4 from the list.
Written by Aiad Asaad on May 17th, 2021
4. What exactly is Garbage Collection?
This interview question to test the knowledge about memory management in python.
In older programming languages, memory allocation was quite manual. Many times when you use variables that are no longer in use or referenced anywhere else in the program, they need to be cleaned from the memory.
In python, The so-called Garbage Collector is created for that.
It does that for you. It automatically frees up space for any variables that are no longer in use or referenced anywhere else in the program.
Written by Aiad Asaad on May 17th, 2021
5. How do you can open a file on python?
Dealing with files is one of the most important skills a programmer should have.
In this question, the programmer should show how to deal with files using python.
To open a file in python you can use the class open("Filename"). After that, you should store it in a variable to read the file content with the methods in the class open() called read.
After reading the file, you must close it with the method close().
Written by Aiad Asaad on May 17th, 2021
6. What does the mode parameter in the open() class do?
This question is to test the knowledge of opening, editing, and creating files.
The mode can be passed in the open class after you enter the filename: open(filename, mode)
The mode is an optional argument. it has a default value "r" for reading files.
It can have three main different values, "r", "w", and "a".
"r" for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
"w" for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
"a" or appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
we can also make a mode for reading and writing by this mode "r+" or "w+". Also, we can make the appending mode with the reading by this "a+".
Finally, if we want to read or write in binary format. we can just add b to the mode instead of "+". Also, we can write and read in binary with this mode "rb+" or "wb+".
Again at the end do not ever forget to close the file with the close() method.
Written by Aiad Asaad on May 17th, 2021
7. What are the methods of reading files in python?
This question is to test the knowledge about reading files with different methods.
At first, using the class open() to create a class object from the file. After that, there are three methods to read from that object.
1- file.read()
2- file.readline()
3- file.readlines()
the first one read() is the best and the fastest one. It reads the whole file and returns it as a string.
Here is an example:
with open(path) as f:
contents = f.read()
When displaying the contents, you will find the whole file as a string.
It also can take a parameter to represent the number of letters you want from the file. for example, if you only need to read the first 20 letters from the file you can store them in a variable named letters_20=file.read(20).
The second one readline() is the same as read(). However, instead of reading the whole file, it reads only one line and returns it as a string. Same as read() it can take a parameter to represent the number of letters you want from the file
The third one readlines is the badest and the slowest one. It read the whole file, then prase each line after that store the lines on a list. It is not recommended at all. As it slow and cost huge memory.
When choosing a method to read it is recommended to choose the read method. Also, it is supported to iterate over the file to read line by line as follows:
with open('foo.txt') as f:
for line in f:
do what you need
pass
Written by Aiad Asaad on May 17th, 2021
8. What is the import statement?
This question to make sure that the programmer can import libraries using the import statement. This is a technical question to make sure that one can use the import statement to utilize the code and structure one’s Python project.
The import statement is used to include libraries, packages or modules. Say for example, if you have written a python function before and you need to use it now. Simply instead of copying and pasting the whole function, you can just use the import statement to activate your function and use it in any other code. This can be done simply by the following two words: import YourFunctionName.
In short, the definition of an import statement is that it will transfer all of the code from one file to another Python file.
For example, let’s suppose that you have two Python files: first.py and second.py. Now, assume that the code in first.py is already written alongside its variables and functions. If you want to use these variables and functions in second.py, you can just import the first.py file and immediately gain access to the variables and functions.
Written by Aiad Asaad on May 17th, 2021
9. How do you can delete or rename a file using python?
This question is a technical question to show the ability to deal with files using python code.
The programmer should know the OS module.
OS stands for operating system. It is a python module that utilizes the code to work easily with the operating system. It provides many things. The programmer at first should import the module. After that, to delete the file there is a method named remove() and to rename the file there is a method named rename. For example, if you have a file named "File_name" and you want to rename it to be "New_file_name". you can use this code.
import os
os.rename( "File_name.extention", "New_file_name.extention" )
The code is simple, at first imports the os module, then used the method rename to rename the file. you can also use the method remove with the file you want to remove as a parameter to remove a certain file.
Written by Aiad Asaad on May 17th, 2021
10. What is Lambda in Python?
This question to make sure that the programmer can write code with a certain syntax.
In python, Lambda is named as an anonymous function meaning that a function is without a name. As we already know that the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python. It has the following syntax:
Syntax: lambda arguments: expression
Some function definitions are simple enough that they can be converted to a lambda function. By doing this, you write fewer lines of code, which is pretty awesome and will come in handy, especially when you're writing and maintaining big programs.
Important note: You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression.
Here is an example of a normal function and the way of writing it using lambda.
def cube(y):
return y*y*y
lambda_cube = lambda y: y*y*y
print(cube(5))
print(lambda_cube(5))
As we can see in the above example both the cube() function and lambda_cube() function behave the same and as intended. Let’s analyze the above example a bit more:
Without using Lambda: Here, both of them return the cube of a given number. But, while using def, we needed to define a function with a name cube and needed to pass a value to it. After execution, we also needed to return the result from where the function was called using the return keyword.
Using Lambda: Lambda definition does not include a “return†statement, it always contains an expression that is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions.
This question can be asked in many different ways for example: "What are the nameless/anonymous functions in python? "
Written by Aiad Asaad on May 17th, 2021
11. What is is the usage of the self word in classes?
This question to test the ability to write a structured class and methods in python.
The word self is used in classes methods to represent the instance of the class. By using the “self†keyword we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.
The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically
Important note:
Self must be provided as a First parameter to the Instance method and constructor. If you don’t provide it, it will cause an error.
Written by Aiad Asaad on May 17th, 2021
12. What is object oriented programming language? and is python support it or not?
This is to assert that the programmer understands the concept of the OOP. This is very important as the OOP is used to code for most of a programmer's educational career.
It first let us take it word by word.
Object means while coding the programmer is using objects to structure the code.
oriented means that the code is focusing on a certain direction to reach a solution.
Together we can say that object-oriented programming (OOP) means that we are using objects to structure and organize the code in a way that facilitates the blocks of codes to solve problems.
A feature of objects is that an object's own procedures can access and often modify the data fields themselves. An example is a class, we can access and modify the data field using the keyword self.
Of course, python supports the OOP as it can use objects to organize the code.
In python, the building block of object-oriented programming is the classes.
Written by Aiad Asaad on May 17th, 2021
13. What is polymorphism?
This question to make sure that the programmer can state the definition of polymorphism.
The word polymorphism means having many forms.
polymorphism is an important feature of the class definition in Python that is utilized when you have commonly named methods across classes or sub-classes.
Polymorphism can be carried out through inheritance, with sub-classes making use of base class methods or overriding them.
There are two types of polymorphism:
1-Overloading
2-Overriding
Overloading: Overloading occurs when two or more methods in one class have the same method name but different parameters.
Overriding: Overriding means having two methods with the same method name and parameters (i.e., method signature). One of the methods is in the parent class and the other is in the child class.
Example
class Fish():
def skeleton(self):
print("The fish's skeleton is made of cartilage.")
class Clownfish():
def skeleton(self):
print("The clownfish's skeleton is made of bone.")
a = Fish()
a.skeleton()
b = Clownfish()
b.skeleton()
Here we can see that the two classes have the same method but with a different print statement. Therefore this is overloading polymorphism.
polymorphism can also occur with the function for example the built-in function len(). we can use many different types of variables to know the length of it for example:
len("string")
List=[1,2,3,4,5]
len(List)
Set={1,2,3,4}
len(Set)
Here we can see the len() function can deal with many different data types which is the definition of polymorphism.
Written by Aiad Asaad on May 17th, 2021
14. What is inheritance in python?
Inheritance will allow access to the child call meaning it can access the attributes and methods of the base. There are many types in the inheritance
Inheritance is the capability of one class to derive or inherit the properties from another class. The benefits of inheritance are:
- It represents real-world relationships well.
- It provides the reusability of a code. We don’t have to write the same code again and again. Also, it allows us to add more features to a class without modifying it.
- It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A.
Here is an example:
class Person(object):
def __init__(self, name):
self.name = name
def getName(self):
return self.name
class Employee(Person):
def isEmployee(self):
return True
emp = Person("Geek1")
print(emp.getName())
emp = Employee("Geek2")
print(emp.getName(), emp.isEmployee())
Here we can see that the employee class is inherited from the person class. We call the person class the parent class and the employee class the child class.
Written by Aiad Asaad on May 17th, 2021
15. What are the types of inheritance in python?
The programmer should know the types of inheritance and how to use them.
There are five types of inheritance. They are classified according to the links between the patent and the child.
The five types are:
- Single Inheritance: Single inheritance enables a derived class to inherit properties from a single parent class, thus enabling code reusability and the addition of new features to existing code.
- Multiple Inheritance: When a class can be derived from more than one base class this type of inheritance is called multiple inheritance. In multiple inheritance, all the features of the base classes are inherited into the derived class.
- Multilevel Inheritance: In multilevel inheritance, features of the base class and the derived class are further inherited into the new derived class. This is similar to a relationship representing a child and a grandfather.
- Hierarchical Inheritance: When more than one derived classes are created from a single base this type of inheritance is called hierarchical inheritance. In this program, we have a parent (base) class and two child (derived) classes.
- Hybrid Inheritance: Inheritance consisting of multiple types of inheritance is called hybrid inheritance.
class School:
def func1(self):
pass
class Student1(School):
def func2(self):
pass
class Multilevel(Student1):
def func2(self):
pass
class Student2(School):
def func3(self):
pass
class Student3(Student1, School):
def func4(self):
pass
We can say that the first two classes separately are in a single inheritance. Also, we can say classes School, student1 and Multilevel separately are in Multilevel Inheritance. The first two classes and the last one separately are in Multiple Inheritance. The classes School, student1 and student2 separately are in Hierarchical Inheritance. If we speak about all of them we can say that they are in Hybrid Inheritance.
Written by Aiad Asaad on May 17th, 2021
16. What is the usage of help() function in python?
One of the most important skills the programmer should have is to learn and discover new libraries and functions and know how to use them.
The help() function is a very good way of knowing all information about built-in functions. It tells you about their parameters and how and why to use them.
The syntax: help(built-in function).
For example, you can see the full documentation of the function len() by running this code line:
help(len(" ")).
One of the most beautiful things about the help is that you can also use it to know everything about an inherited class. It will let you know what are the inherited method, the parents and all the details.
Written by Aiad Asaad on May 17th, 2021