Top 20 Python Interview Questions And Answers
Dot Net Tricks Interview Preparation Placement
Interview Skills preparation & Placment
Q.1 What is Python?
Python is a dynamic, interpreted, easy to learn, readable high-level programming language. It was created in 1991 by Guido van Rossum. It is a versatile programming language and allows you to do many things, both big and small. Python is being used in different areas like Machine learning, Data analysis, Web Development, Automation, and many more. If you are beginner in programming, then python suits your career.
Q.2 What are the major features of Python?
There are following features of Python:
- Dynamic Typing - Python doesn't have something like type declaration of variable, it automatically tracks the objects when your program runs.
- No Manual Memory Management - Python uses garbage collector rather than manual memory management. The allocation and reclamation of memory from objects which are not referenced further are collected by Pythons garbage collector. Objects grow and shrink on demand.
- Essential object types - Python provides basic data structures such as lists, dictionaries tuples, and string as an essential part of language and they are versatile and easy to use.
- Useful Packages - Python has large collection of packages for different purposes and has great support in the community. Python has packages for everything searching, sorting, data analysis, web development, machine learning, socket programming, NLP, and many more.
- Programming-in-large-support - Python includes tools such as class, modules, and exceptions. These tools enable you to modularize your system and use OOP to reuse and use your logic in code for customization, handle events, and errors.
Q.3 How Python is different from other languages like Perl or Java?
Python is often compared to similar tools whereas there are numerous tools that can be used like Tcl, Pearl, and Java. But Python is:
- More powerful than Tcl so it is suitable for large system developments.
- More readable and simple to understand syntax as compared to Perl. The readability is high and easy to maintain large codebase.
- We can't compare it with java at head-on. Python is a scripting language whereas Java is system language like C++.
Q.4 What is the difference between a Python module and package?
A module in Python is a single file that you can import in your Python program and use it by using the "import" keyword followed by the filename. A package is a collection of modules that means it contains more than one Python module. Packages can be nested up to any depth with directories containing a special file called __init__.py. Modules are created and used when you want to share small code of functions everywhere in your project. Suppose you have a bunch of functions querying database so you can put all at one place and can import that file wherever you want that will make it more maintainable and easier to debug. Packages are vaster and contain lots of features some of popular packages are OpenCV, pandas, etc. Packages have special purpose to server in program.
Q.5 How to declare and access a docstring?
Declaring: Docstrings are declared using """ triple double quotes and ends with """ triple double-quotes. All functions should have a docstring.
Accessing: Docstrings can be accessed via help function of Python to access the docstring or you can use the __doc__ method.
Code
def new_function(): """Piece of information a docstring.""" return None print("with __doc__:") print(new_function.__doc__) print("with help:") help(new_function)
Output
with __doc__: Piece of information a docstring.. with help: Help on function new_function in module __main__: new_function() Piece of information a docstring.
Q.6 What is LGB rule for name resolution in Python?
References are searched at most 3 scopes: local, global, and built -in. When a name reference inside a function then it’s in local scope by default. If you want to use global variables then before use declare them as global inside function. This concept of name resolution called LGB rule. When you use a named reference inside function python first search it in Local(L) scope, then the Global(G) and then the built-in (B) and will stop at the first place where name is found.
- Built-in (Python)
- Predefined names - open, len, etc.
- Global (Module)
- Names assigned at top - level of a module.
- Name declared "global" in function.
- Local (Function)
- Name assigned inside a function (def)
Code
# global scope A = 56 # A and fun assigned in module: global def fun (B): # B and D assigned inside function: locals # local scope D = A + B # A is not assigned, so it's a global return D fun(1) # fun in module: result = 57
Q.7 What is global declaration in python?
There is only one thing in python that is like declaration is the "global" keyword. "global" means a name has scope at the top level of module file. If you want to use a value of that variable inside a function then only you should declare it as Global. Global names can be referenced inside function without declaration. The global keyword is followed by one or more names comma-separated inside a function body only. The names which are assigned or referenced inside function body are mapped to module-level scope.
Code
A, B = 1, 2 # global values sum = 0 def global_values(): global sum # Global declaration sum = A + B # no declaration needed as not an assignment
Explanation: -
Here sum, A and B are all global inside function global_values. A and B are global because we haven't assigned it and "sum" is global because we declared it so and listed it in a global statement.
Q.8 What is Lambda in Python?
Beside def python provides lambda that can generate function objects. "def" keyword in Python is used for declaration of a function whereas lambda is basically to create an anonymous function. Lambda function contains one or more arguments followed by an expression. Function objects by def and lambda are exactly the same. But lambda has few things that make it different from normal function.
- Lambda is an expression, not a statement
- Lambda can appear in places where a def can't like inside a list constant. Lambda returns a function that can be assigned a name.
- Lambda bodies are a single expression, not a block of statements
- Lambda is not like block of statements in def but similar to what you write in return statement of def.
It follows the following syntax
def func(a, b, c) : return a + b + c func( 1, 2, 3) 6 f = lambda a, b, c: a + b + c f(2, 3, 4) 9
Q.9 What is the equivalent of procedures in python?
In python, it's not mandatory that you return something at end of function when you don't return the function returns None object automatically. Functions with such behavior in Python are equivalent to procedures in some languages. Procedure are meant to do their work without computing a useful result. For example, appending an item to a list won't, and assigning it to a name won't raise error but you do get 'None' object.
Example Code
mylist = [1, 2, 3 ] mylist = mylist.append(4) print mylist None
Q.10 What are decorators?
A Python decorator is to add functionality to an existing code. A decorator takes a function as argument adds some functionality and returns the function.
Example Code
def safe_divide(func): def inside(a,b): print("Dividing two values",a,"and",b) if b == 0: print("You can not divide by zero") return return func(a,b) return inner @safe_divide def divide(a,b): return a/b We can use the symbol '@' then the decorator name to wrap a function. In layman term we can say our divide function is a gift and safe divide is wrapper i.e, a decorator for the function.
Q.11 Why to use modules in Python?
In simplest way module provides a way to organize components into system. Modules do have an important role in python:
Code reusability
The code in a module file is persistent and can be reused, reloaded as many times as needed. Modules can be easily imported in any python file and used.
System namespace partitioning
Modules are highest level or program organization unit. Everything lives in a module code you execute and some objects. Modules are natural tools for grouping components.
Implementing shared service or data
We can provide a global data structure that can be used by more than one function and can be imported by many clients
Q.12 How to achieve multi-threading in Python?
Python does gives you a multi-threading package and you can use it, but it’s not considered as a good idea. Python has Global Interpreter Lock (GIL). GIL makes sure that only one thread executes at a time and then it will switch to another thread. The switching between the threads may seem like multi-threading but it’s just faster switching which human eye can't recognize and we think like they are getting executed parallel. But all will be executing the same CPU core. The switching actually puts extra overhead in code execution. So, if you are thinking of speeding up your code with Python's threading library then it's not a good idea.
Q.13 What is the significance of the subprocess in Python?
The subprocess module in Python is useful in executing programs or piece of code that is written in some other language. You can create a subprocess and execute the file or code. It helps to obtain input/output/error pipes with exit codes.
Example: C Program
Code
#include< stdio.h> int main() { printf("Hello World from C Program"); // returning with 0 would raise an exception in Python return 0; }
Python 3 program to execute C program
Code
import subprocess import os def executeC(): s = subprocess.check_call("gcc helloworld.c -o out1;./out1", shell = True) print(", return code : -", s)
Output
Hello World from C Program, return code : - 0
Q.14 What is init method in a python class?
__init__: Reserved method in python classes. It is similar to writing a constructor in other object-oriented languages. This method called when you create an instance of a class and you can pass parameters that will be used to initialize the attributes.
Usage: Let's say you are creating a car racing game. For that we should have a car and car have some basic attributes like "color", "company", "top speed", "mileage" etc.
Code
class Taxi(object): def __init__(self, name, domain, total_employee, founder): self.name = name self.domain = domain self.total_employees = total_employee self.founder = founder def create_company(self): print("company created") def increment_employee(self, gear_type): print("employees increased") " add employee functionality here" Let's create different cars. Code car1 = Company("honda city", "Infrastructure", 100, "rahul") car2 = Company("Numberica", "IT", 180, "rajiv")
We have created two different types of company objects with the same class. While creating the instance we passed arguments "honda city", "Infrastructure", 100 these arguments are passed to "__init__" method to initialize the instance of car class. "self" points or can be used to access the instance of the class. It maps and ties the attributes with the given arguments.
Q.15 Explain the inheritance in Python with example?
Re-usability is one of the major advantages of Object-Oriented Programming. To achieve re-usability Inheritance is one of the mechanisms. Inheritance is a mechanism where a class usually called as parent class or super class is inherited by another class which is known as child class or subclass. Subclass can add some attributes to its own class as well use the attributes of parent class. We will try to understand more on inheritance with the help of below example
Example to demonstrate inheritance:
class People(object): # constructor def __init__(self, name): self.name = name # To get name def get_name(self): return self.name # To check if this person is employee def is_staff(self): return False # Inheriting People Class class Staff(People): #return true def is_staff(self): return True staff1 = People("Staff1") # Object of People print(staff1.get_name(), staff1.is_staff()) staff2 = Staff("Staff2") # Object of Staff print(staff2.get_name(), staff2.is_staff())
output
(Staff1, False) ('Staff2', True)
Article Source:-
https://www.dotnettricks.com/learn/python/python-interview-questions-and-answers
#python #top20 #questions #pythondeveloper #interview #coding #PythonProgramming
#programing #dotnettricks
Thank you for sharing