Python oop interview questions – Python Interview Questions on Introduction to Python

Python oop interview questions: We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Introduction to Python

Python

  • Python is a very popular programming language. It is known for being an interactive and object-oriented programming language.
  • Free software, an open-source language with a huge number of volunteers who are working hard to improve it. This is the main reason why the language is current with the newest trends.
  • It has several libraries which help build powerful code in a short span of time.
  • It is a very simple, powerful, and general-purpose computer programming language.
  • Python is easy to leam and easy to implement.
  • Well-known corporations are using Python to build their site. Some of the wells know websites built-in Python are as follows:
  1. Google
  2. Quora
  3. Yahoo!
  4. Instagram
  5. Survey Monkey
  6. You Tube
  7. Dropbox
  8. Reddit
  9. Spotify
  10. Bitly
  • The main reason for the popularity of the Python programming language is the simplicity of the code.
  • You require no skills to leam Python.

Question 1.
What can you do with python?
Answer:
There is no limit to what can be achieved with the help of Python Programming:

  • Python can be used for small or large, online or offline applications.
  • Developers can code using fewer lines of code compared to other languages.
  • Python is widely used for developing web applications as it has a dynamic system and automatic memory management is one of its strongest points.
  • Some of the very well-known Python frameworks are Pyramid, Django, and Flask.
  • Python is also used for a simple scripting and scientific modeling and big data applications:
  • It is the number one choice for several data scientists.
  • Its libraries such as NumPy, Pandas data visualization libraries such as Matplotlib and Seaborn have made Python very popular in this field.
  • Python also has some interesting libraries such as Scikit-Leam, NLTK, and TensorFlow that implement Machine learning Algorithms.
  • Video Games can be created using the PyGame module. Such applications can run on Android devices.
  • Python can be used for web scrapping.
  • Selenium with Python can be used for things like opening a browser or posting a status on Facebook.
  • Modules such a Tkinter and PyQt allow you to build a GUI desktop application.

Question 2.
Why is Python considered to be a highly versatile programming language?
Answer:
Python is considered to be a highly versatile programming language because it supports multiple models of programming such as:

  • OOP
  • Functional
  • Imperative
  • Procedural

Question 3.
What are the advantages of choosing Python over any other programming language?
Answer:
The advantages of selecting Python over other programming languages are as follows:

  • Extensible in C and C++.
  • It is dynamic in nature.
  • Easy to learn and easy to implement.
  • Third-party operating modules are present: As the name suggests a third party module is written by a third party which means neither you nor the python writers have developed it. However, you can make use of these modules to add functionality to your code.

Question 4.
What do you mean when you say that Python is an interpreted language?
Answer:
When we say that Python is an interpreted language it means that python code is not compiled before execution. Code written in compiled languages such as Java can be executed directly on the processor because it is compiled before runtime and at the time of execution it is available in the form of machine language that the computer can understand. This is not the case with Python. It does not provide code in machine language before runtime. The translation of code to machine language occurs while the program is being executed.

Question 5.
Are there any other interpreted languages that you have heard of?
Answer:
Some frequently used interpreted programming languages are as follows:

  • Python
  • Pearl
  • JavaScript
  • PostScript
  • PHP
  • PowerShell

Question 6.
Is Python dynamically typed?
Answer:
Yes, Python is dynamically typed because in a code we need not specify the type of variables while declaring them. The type of a variable is not known until the code is ‘executed.

Question 7.
Python is a high-level programming language? What is a need for high-level programming languages?
Answer:
High-level programming languages act as a bridge between the machine and humans. Coding directly in machine language can be a very time-consuming and cumbersome process and it would definitely restrict coders from achieving their goals. High-level programming languages like Python, JAVA, C++, etc are easy to understand. They are tools that programmers can use for advanced-level programming. High-level languages allow developers to code complex code that is then translated to machine language so that the computer can understand what needs to be done.

Question 8.
Is it true that Python can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java?
Answer:
Yes

Question 9.
What are the different modes of programming in Python?
Answer:
There are two modes of programming in Python:
1. Interactive Mode Programming:
In this, we invoke the interpreter without passing any script or python file. We can start the Python command-line interpreter or the Python shell in IDLE and start passing instructions and get instant results.
2. Script Mode of Programming:
Saving code in a Python file. When the script is executed the interpreter is invoked and it is active as long as the script is running. Once all the instructions of the script are executed the interpreter is no longer active.

Question 10.
Draw a comparison between Java and Python.
Answer:

1. Java is compiled and Python is interpreted:
Both Java and Python are compiled down to the byte code on the virtual machine. However, in the case of Python, this happens automatically during runtime whereas Java has a separate program – javac to accomplish this task. This also means that if speed is the major concern in your project then Java may have an edge over Python but you cannot deny that Python allows faster development (as you will leam in the next point).

2. Java is Statistically typed and Python is dynamically typed:
While coding in Python, it is not required to declare the type of the variable. This makes Python easy to write and read but it can be difficult to analyze. The developer is able to code faster and the task can be accomplished in fewer lines of code. Developing applications in Python can be much faster Python than Java. However, Java’s static type system makes it less prone to bugs.

3. Writing style:
Both Java and Python follow different writing styles. Java encloses everything in braces whereas Python follows indentation that makes the code neat and readable. Indentation also determines the code execution.

4. Both Java and Python are efficient languages:
Both Java and Python are being widely used for web development frameworks. Developers are able to create complex applications that can handle high traffic.

5. Both Java and Python have a strong community and library support:
Both are open source languages having communities that are offering support and contribution to the language. You can easily find a library for almost anything.

6. Python can be more budget-friendly:
Since Python is dynamically typed, it makes development a fast process as a result of which developers can expect to develop an application in a record time thereby lowering down the cost of development.

7. Java is the more preferred language in mobile development:
Android app development is mostly done using Java and XML. However, there are libraries like Kivy which can be used along with Python code in order to make it compatible with android development.

8. Python is preferred for Machine learning, the Internet of things, ethical hacking, data analysis, and artificial intelligence:
Python has very specialized libraries and general flexibility and hence it has become the number one choice for projects that have a bias towards deep learning, machine learning, and image recognition.

9. Java and Python both support OOP:

10. LOC in Java is more than in Python: Let’s have a look at how we would go about printing simple Hello World in Java:

public class HelloWorld 
{ 
  public static void main(String [ ] args) 
{ 
  System.out.println("Hello World"); 
} 
  } 
Whereas in python we just write one line of code: print("Hello World")

11. Java is more difficult to learn as compared to Python:
Python was developed with the main focus on making it easy to learn.

12. Java is stronger when it comes to connectivity with database:
The database access layer of Java is very strong and is compatible with almost any database. Python database connectivity is not as strong as Java.

13. Security:
Java gives high priority to security which is why it is a preferred language for applications that require security but a good developer can code a secure application in Python also.

Question 11.
Once Python is installed, how can we start working on code?
Answer:
After Python is installed there are three ways to start working on code:

1. You can start an interactive interpreter from the command line and start writing the instructions after the »> prompt.

2. If you intend to write a code of several lines then it would be a wise decision to save your file or script with the .py extension and you can execute these files from the command line. Multiline programs can be executed on an interactive interpreter, also but it does not save the work.

3. Python also has its own GUI environment known as Integrated Development Environment (IDLE). IDLE helps programmers write code faster as it helps with automatic indenting and highlights different keywords in different colors. It also provides an interactive environment. It has two windows: the shell provides an interactive environment whereas the editor allows you to save your scripts before executing the code written in it.

Question 12.
What is the function of the interactive shell?
Answer:
The interactive shell stands between the commands given by the user and the execution done by the operating system. It allows users to use easy shell commands and the user need not be bothered about the complicated basic functions of the Operating System. This also protects the operating system from incorrect usage of system functions.

Question 13.
How to exit interactive mode?
Answer:
Ctrl+D or exit( ) can be used to quit interactive mode.

Question 14.
Which character set does Python use?
Answer:
Python uses a traditional ASCII character set.

Question 15.
What is the purpose of indentation in Python?
Answer:
Indentation is one of the most distinctive features of Python. While in other programming languages, developers use indentation to keep their code neat but in the case of Python, indentation is required to mark the beginning of a block or to understand which block the code belongs to. No braces are used to mark blocks of code in Python. Blocks in code are required to define functions, conditional statements, or loops. These blocks are created simply by the correct usage of spaces. All statements that are the same distance from the right belong to the same block.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 1

Remember:

  • The first line of the block always ends with a semicolon (:).
  • Code under the first line of the block is indented. The preceding diagram depicts a scenario of indented blocks.
  • Developers generally use four spaces for the first level and eight spaces for a nested block, and so on.

Question 16.
Explain Memory Management in Python.
Answer:
Memory management is required so that a partial or complete section of the computer’s memory can be reserved for executing programs and processes. This method of providing memory is called memory allocation. Also, when data is no longer required, it must be removed. Knowledge of memory management helps developers develop efficient code.

Python makes use of its private heap space for memory management. All object structures in Python are located in this private heap (which is not accessible by the programmer). Python’s memory manager ensures that this heap space is allocated judiciously to the objects and data structures. An in-built garbage collector in Python recycles the unused memory so that it is available in heap space.

Everything in Python is an object. Python has different types of objects, such as simple objects which consist of numbers and strings, and container objects such as diet, list, and user-defined classes. These objects can be accessed by an identifier- name. Now, let’s have a look at how things work.
Suppose, we assign the value of 5 to a variable a:
a = 5
Here, ‘5’ is an integer object in memory, and ‘a’ has reference to this integer object.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 2

In the above illustration, the id( ) function provides a unique identification number of an object. This unique identification number is an integer value that will remain unique and constant for the object during its lifetime. Two objects with non-overlapping lifetimes can have the same id( ) value.

The id for integer object 5 is 140718128935888. Now we assign the same value 5 to variable b. You can see in the following diagram that both a and b have to refer to the same object.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 3

Now, let us say:
c = b.
This means, c too will have reference to the same object.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 4

Now, suppose we perform the following operation: a =a+1

This means that a is now equal to 6 and now refers to a different object.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 5

Some amount of memory organization is done for every instruction. The underlying operating system allocates some amount of memory for every operation. The Python interpreter gets its share of memory depending on various factors such as version, platform, and environment.

The memory assigned to the interpreter is divided into the following:

1. Stack:
a. Here all methods are executed.
b. References to objects in the heap memory are created in stack memory.
2. Heap:
a. The objects are created in Heap memory.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 6

Now let’s have a look at how things work with the help of an example. Look at the following piece of the code:

def function1(x): 
    value1 = (x + 5)* 2 
    value2 = function2(value1) 
      return value2 
def function2(x): 
   x = (x*10)+5 
   return x 
   x = 5 
final_value = function1 (x) 
print ("Final value = ", final_value)

Now, let’s see how this works. The program’s execution starts from the main which in this case is:

x = 5 
final_value = function1 (x) 
print ("Final value = ", final_value)

Step 1: execute x =5
This creates integer object 5 in the heap and reference to this object i.e. x is created in the main stack memory.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 7

Step 2: is to execute final_value = function1(x)
This statement calls function1( ).

def function1 (x):
value1 = (x + 5)* 2
value2 = function2(value1)
return value2

In order to execute function1 ( ) a new stack frame is added to the memory. Till the time function1( ) is being executed the lower stack frame of x referencing to 5 is put on hold. The integer value 5 is passed as a parameter to this function.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 8

Now, value1 = (x+5)* 2 = (5+5)*2 = 10*2 = 20

Python Interview Questions and Answers on Introduction to Python chapter 1 img 9

function1( ) assigns the value of 50 to value1.
The next step is: value2 = function2(value1)

Here function2( ) is called to evaluate a value that needs to be passed on to value2. In order to accomplish this, another memory stack is created. The integer object value1 having a value of 20 is passed as a reference to function2.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 10

def function2 (x) : 
x = (x*10)+5 
return x

The function function2( ) evaluates the following expression and returns the value:

x = (x*10)+5
x = (20*10)+5 = (200)+5 = 205

 

Python Interview Questions and Answers on Introduction to Python chapter 1 img 11

The function function2( ) is fully executed and value 205 is assigned to value2 in function 1. So, now the stack for function(2) is removed.

 

Python Interview Questions and Answers on Introduction to Python chapter 1 img 12

Now, function1( ) will return the value 205 and it will be assigned to the final_value in the main stack.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 13

Here it is important to note that you would see that x exists in the main as well as in different functions but the values don’t interfere with each other as each x is in a different memory stick.

Question 17.
Explain Reference counting and Garbage collection in Python.
Answer:
Unlike languages like C/ C++, the process of allocation and deallocation of memory in Python is automatic. This is achieved with the help of reference counting and garbage collection.

As the name suggests, reference counting counts the number of times an object is referred to by other objects in a program. Every time a reference to an object is eliminated, the reference count decreases by 1. As soon as the reference count becomes zero, the object is deallocated. An object’s reference count decreases when an object is deleted, the reference is reassigned or the object goes out of scope. The reference count increases when an object is assigned a name or placed in a container.

Garbage collection on the other hand allows Python to free and reclaim blocks of memory that are no longer of any use. This process is carried out periodically. The garbage collector runs while the program is being executed and the moment the reference count of an object reaches zero, the garbage collector is triggered.

Question 18.
What are multi-line statements?
Answer:
All the statements in Python end with a newline. If there is a long statement, then it is a good idea to extend it over multiple lines. This can be achieved using the continuation character (\).

Explicit line continuation is when we try to split a statement into multiple lines whereas in the case of implicit line continuation we try to split parentheses, brackets, and braces into multiple lines.
Example for multiple line statements:

Explicit:

>>> first_num = 54
>>> second_num = 879
>>> third__num = 8 76
>>> total = first_num +\
               second_num+\
               third_num
>>> total
1809
>>>
Implicit:
>>> weeks=['Sunday' ,
                      'Monday',
                      'Tuesday',
                      'Wednesday',
                      'Thursday' ,
                      'Friday',
                      'Saturday']
>>> weeks
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursdy', 'Friday', 'Saturday']
>>>

Question 19.
What are the types of error messages in Python?
Answer:
While working with Python you can come across:

1. Syntax-error
2. Run-time errors

Syntax errors are static errors that are encountered when the interpreter is reading the program. If there is any mistake in the code then the interpreter will display a syntax error message and the program will not be executed.
Run time errors as the name suggests are dynamic errors. They are detected while the program is executing. Such errors are bugs in the program that may require design change such as running out of memory, dividing a number by zero, and so on.

Question 20.
What are the advantages of Python’s IDLE environment?
Answer:
The Python IDLE environment has the following:

  • Python’s interactive mode
  • Tools for writing and running programs
  • It comes along with the text editors which can be used for working on scripts

Question 21.
What is a comment?
Answer:
A comment is one or more statements used to provide documentation or information about a piece of code in a program. In Python one-line comments start with ‘#’.

Question 22.
Is Python a case-sensitive programming language?
Answer:
Yes

General Python Concepts

Question 23.
How is Python executed?
Answer:
Python files are compiled to bytecode, which is then executed by the host.
Alternate Answer: Type python <sourcefile>.py at the command line.

Question 24.
What is the difference between .py and .pyc files?
Answer:
.py files are Python source files, .pyc files are the compiled bytecode files that are generated by the Python compiler

Question 25.
How do you invoke the Python interpreter for interactive use?
Answer:
python or pythonx.y where x.y is the version of the Python interpreter desired.

Question 26.
How are Python blocks defined?
Answer:
By indents or tabs. This is different from most other languages which use symbols to define blocks. Indents in Python are significant.

Question 27.
What is the Python interpreter prompt?
Answer:
Three greater-than signsQuestion>>> Also, when the interpreter is waiting for more input the prompt changes to three periods …

Question 28.
How do you execute a Python Script?
Answer:
From the command line, type python <scriptname>.py or pythonx.y <scriptname>.py where the x.y is the version of the Python interpreter desired.

Question 29.
Explain the use of tryQuestionexceptQuestionraise, and finally:
Answer:
Try, except and finally blocks are used in Python error handling. Code is executed in the try block until an error occurs. One can use a generic except block, which will receive control after all errors, or one can use specific exception handling blocks for various error types. Control is transferred to the appropriate except block. In all cases, the final block is executed. Raise may be used to raise your own exceptions.

Question 30.
Illustrate the proper use of Python error handling.
Answer:
Code Example
try:
… # This can he any code
except:
… # error handling code goes here
finally:
… # code that will be executed regardless of exception handling goes here.

Question 31.
What happens if an error occurs that is not handled in the except block?
Answer:
The program terminates, and an execution trace is sent to sys. stderr.

Question 32.
How are modules used in a Python program?
Answer:
Modules are brought in via the import statement.

Question 33.
How do you create a Python function?
Answer:
Functions are defined using the def statement. An example might be deffoo(bar):

Question 34.
How is a Python class created?
Answer:
Classes are created using the class statement. An example might be class aardvark(foobar):

Question 35.
How is a Python class instantiated?
Answer:
The class is instantiated by calling it directly. An example might be myclass=aardvark(5)

Question 36.
In a class definition, what do the init ( ) functions do?
Answer:
It overrides any initialization from an inherited class and is called when the class is instantiated.

Question 37.
How does a function return values?
Answer:
Functions return values using the return statement.

Question 38.
What happens when a function doesn’t have a return statement? Is this valid?
Answer:
Yes, this is valid. The function will then return a None object. The end of a function is defined by the block of code is executed (i.e., the indenting) not by any explicit keyword.

Question 39.
What is the lambda operator?
Answer:
The lambda operator is used to create anonymous functions. It is mostly used in cases where one wishes to pass functions as parameters or assign them to variable names.

Question 40.
Explain the difference between local and global namespaces.
Answer:
Local namespaces are created within a function when that function is called. Global namespaces are created when the program starts.

Question 41.
Name the four main types of namespaces in Python? Answer:

  • Global,
  • Local,
  • Module and
  • Class namespaces.

Question 42.
When would you use triple quotes as a delimiter? Answer:
Triple quotes ” ” ” or are string delimiters that can span multiple lines in Python. Triple quotes are usually used when spanning multiple lines, or enclosing a string that has a mix of single and double quotes contained therein.