Python Interview Questions and Answers
Q1. What is Python?
Answer: Python is a high-level and object-oriented programming language with unified semantics designed primarily for developing apps and web. It is the core language in the field of Rapid Application Development (RAD) as it offers options such as dynamic binding and dynamic typing.
Q2. What are the benefits of Python?
Answer:The benefits of Python are as follows:
- Speed and Productivity: Utilizing the productivity and speed of Python will enhance the process control capabilities and possesses strong integration.
- Extensive Support for Libraries: Python provides a large standard library that includes areas such as operating system interfaces, web service tools, internet protocols, and string protocols. Most of the programming tasks are already been scripted in the standard library which reduces effort and time.
- User-friendly Data Structures: Python has an in-built dictionary of data structures that are used to build fast user-friendly data structures.
- Existence of Third Party Modules: The presence of third party modules in the Python Package Index (PyPI) will make Python capable to interact with other platforms and languages.
- Easy Learning: Python provides excellent readability and simple syntaxes to make it easy for beginners to learn.
Q3. What are the key features of Python?
Answer: The following are the significant features of Python, and they are: Interpreted Language: Python is an interpreted language that is used to execute the code line by line at a time. This makes debugging easy.
Highly Portable: As Python can run on different platforms such as Unix, Macintosh, Linux, Windows, and so on. So, we can say that it is a highly portable language.
Extensible: It ensures that the Python code can be compiled on various other languages such as C, C++ and so on.
GUI programming Support: It implies that the Python provides support to develop graphical user interfaces.
Q4. What type of language is Python? Programming or Scripting?
Answer:Python is suitable for scripting, but in general it is considered as a general-purpose programming language.
Q5. What are the applications of Python?
Answer: The applications of Python are as follows:
- GUI based desktop applications
- Image processing applications
- Business and Enterprise applications
- Prototyping
- Web and web framework applications
Q6. What is the difference between list and tuple in Python?
Answer: The difference between tuple and list are as follows:
- List
- The list is mutable (can be changed)
- These lists performance is slower
- Syntax: list_1 = [20, ‘Mindmajix’, 30] Tuple
- A tuple is immutable (remains constant)
- Tuple performance is faster when compared to lists
- Syntax: tup_1 = (20, ‘Mindmajix’, 30)
Q7. What are the global and local variables in Python?
Answer: Global Variables in Python: The variables that are declared outside the function are called global variables. These variables can be accessed or invoked by any function in the program.
Q8. Define PYTHON PATH?
Answer:PYTHONPATH is an environmental variable that is used when we import a module. Suppose at any time we import a module, PYTHONPATH is used to check the presence of the modules that are imported in different directories. Loading of the module will be determined by interpreters.
Q9. What are the two major loop statements?
Answer: for and while
Interview Questions based on Experience - Click here - Python Interview Questions and Answers
Q10. What do you understand by the term PEP 8?
Answer: PEP 8 is the Python latest coding convention and it is abbreviated as Python Enhancement Proposal. It is all about how to format your Python code for maximum readability.
Q11. How memory management is done in Python?
Answer:In Python memory management is done using private heap space. The private heap is the storage area for all the data structures and objects. The interpreter has access to the private heap and the programmer cannot access this private heap. .
The storage allocation for the data structures and objects in Python is done by the memory manager. The access for some tools is provided by core API for programmers to code.
The built-in garbage collector in Python is used to recycle all the unused memory so that it can be available for heap storage area.
Q12. Java vs Python
Answer: The major difference between Java and Python are as follows:
- Java
- In Java, we need to write a long code to print something.
- In Java we need to put a semicolon at the end of the statement and also code must be placed in curly braces.
- In Java, we need to declare the type for each variable
- Java is not easy to use because of its larger coding
- Java Database Connectivity (JDBC) is more popular and used most commonly. Python
- In Python coding is simple and smaller when compared to Java
- Whereas, in Python indentation is mandatory as it improves the readability of the code.
- In this case, codes are dynamically typed and this is also known as duck typing
- In Python, it is very easy to code and perform very easily.
- In Python database access layers are weaker when compared to Java.
Q13. Define modules in Python?
Answer: Module is defined as a file that includes a set of various functions and Python statements that we want to add in our application.
Q14. What are the built-in types available in Python?
Answer: The built-in types in Python are as follows:
- Integer
- Complex numbers
- Floating-point numbers
- Strings
- Built-in functions
Q15. What are Python Decorators?
Answer:Decorator is the most useful tool in Python as it allows programmers to alter the changes in the behavior of class or function.
Q16. How do we find bugs and statistical problems in Python?
Answer: We can detect bugs in python source code using a static analysis tool named PyChecker. Moreover, there is another tool called PyLint that checks whether the Python modules meet their coding standards or not.
Q17. 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
Q18. How do you invoke the Python interpreter for interactive use?
Answer:By using python or pythonx.y we can invoke Python interpreter. where x.y is the version of the Python interpreter.
Q19. Define String in Python?
Answer:tring in Python is formed using a sequence of characters. Value once assigned to a string cannot be modified because they are immutable objects. String literals in Python can be declared using double quotes or single quotes.
Q20. What do you understand by the term namespace in Python?
Answer: A namespace in Python can be defined as a system that is designed to provide a unique name for every object in python. Types of namespaces that are present in Python are:
- Local namespace
- Global namespace
- Built-in namespace
Scope refers to the availability and accessibility of an object in the coding region.
Q21. How do you create a Python function?
Answer:Functions are defined using the def statement.
An example might be def foo(bar):
Q22. Define iterators in Python?
Answer: In Python, an iterator can be defined as an object that can be iterated or traversed upon. In another way, it is mainly used to iterate a group of containers, elements, the same as a list.
Q23. How does a function return values?
Answer:Functions return values using the return statement.
Q24. Define slicing in Python?
Answer:Slicing is a procedure used to select a particular range of items from sequence types such as Strings, lists, and so on.
Q25. How can Python be an interpreted language?
Answer: As in Python the code which we write is not machine-level code before runtime so, this is the reason why Python is called as an interpreted language.
Q26. 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.
Q27. Define package in Python?
Answer: In Python packages are defined as the collection of different modules
Q28. How can we make a Python script executable on Unix?
Answer: In order to make a Python script executable on Unix, we need to perform two things. They are:
Script file mode must be executable and
The first line should always begin with #.
Q29. Which command is used to delete files in Python?
Answer: OS.unlink(filename) or OS.remove(filename) are the commands used to delete files in Python Programming.
Q30. Define pickling and unpickling in Python?
Answer: Pickling in Python: The process in which the pickle module accepts various Python objects and converts into a string representation and dumps the file accordingly using dump function is called pickling.
Unpickling in Python: The process of retrieving actual Python objects from the stored string representation is called unpickling.
Q31. 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.
Q32. What is a boolean in Python?
Answer: Boolean is one of the built-in data types in Python, it mainly contains two values, and they are true and false.
Python bool() is the method used to convert a value to a boolean value.
Q33. What is Python String format and Python String replace?
Answer:Python String Format: The String format() method in Python is mainly used to format the given string into an accurate output or result.
Syntax for String format() method:
template.format(p0, p1, ..., k0=v0, k1=v1, ...)
Python String Replace: This method is mainly used to return a copy of the string in which all the occurrence of the substring is replaced by another substring.
Q34. Name some of the built-in modules in Python?
Answer: The built-in modules in Python are:
sys module
OS module
random module
collection module
JSON
Math module
Q35. What are the functions in Python?
Answer:In Python, functions are defined as a block of code that is executable only when it is called. The def keyword is used to define a function in Python.
Q36. What are Dict and List comprehensions in Python?
Answer:These are mostly used as syntax constructions to ease the creation of list and dictionaries based on existing iterable.
Q37. Define the term lambda?
Answer:Lambda is the small anonymous function in Python that is often used as an inline function.
Q38. 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.
Q39. Define self in Python?
Answer: In Python self is defined as an object or an instance of a class. This self is explicitly considered as the first parameter in Python. Moreover, we can also access all the methods and attributes of the classes in Python programming using self keyword.
Q40. What is _init_?
Answer: The _init_ is a special type of method in Python that is called automatically when the memory is allocated for a new object. The main role of _init_ is to initialize the values of instance members for objects.
Q41. Define generators in Python?
Answer: : The way of implementing an effective representation of iterators is known as generators. It is only the normal function that yields expression in the function.
Q42. Define docstring in Python?
Answer:The docstring in Python is also called a documentation string, it provides a way to document the Python classes, functions, and modules.
Q43. How do we convert the string to lowercase?
Answer: lower() function is used to convert string to lowercase.
Q44. How to remove values from a Python array?
Answer: The elements can be removed from a Python array using remove() or pop() function. The difference between pop() and remove() will be explained in the below example.
Q45. What is Try Block?
Answer:A block which is preceded by the try keyword is known as a try block
Q46. Why do we use the split method in Python?
Answer:split() method in Python is mainly used to separate a given string.
Q47. How can we access a module written in Python from C?
Answer: We can access the module written in Python from C by using the following method.
Q48. How do you copy an object in Python?
Answer:To copy objects in Python we can use methods called copy.copy() or copy.deepcopy().
Q49. How do we reverse a list in Python?
Answer: By using list.reverse(): we can reverse the objects of the list in Python.
Q
Q50. How can we debug a Python program?
Answer:By using the following command we can debug the Python program $ python -m pdb python-script.py
Q51Q. Write a program to count the number of capital letters in a file?
Answer: with open(SOME_LARGE_FILE) as countletter:
count = 0
text = countletter.read()
for character in text:
if character.isupper():
count += 1
QQ52. Write a program to display the Fibonacci sequence in Python?
Answer: # Displaying Fibonacci sequence
n = 10
# first two terms
n0 = 0
n1 = 1
#Count
x = 0
# check if the number of terms is valid
if n <= 0:
print("Enter positive integer")
elif n == 1:
print("Numbers in Fibonacci sequence upto",n,":")
print(n0)
else:
print("Numbers in Fibonacci sequence upto",n,":")
while x < n:
print(n0,end=', ')
nth = n0 + n1
n0 = n1
n1 = nth
x += 1
Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
Q53Q. Write a program in Python to produce Star triangle?
Answer:
The code to produce star triangle is as follows: def pyfun(r): for a in range(r): print(' '*(r-x-1)+'*'*(2*x+1)) pyfun(9) Output: * *** ***** ******* ********* *********** ************* *************** *****************
Q54. Write a program to check whether the given number is prime or not?
Answer:The code to check prime number is as follows:
# program to check the number is prime or not n1 = 409 # num1 = int(input("Enter any one number: ")) # prime number is greater than 1 if n1 > 1: # check the following factors for x is in range of(2,num1): if (n1 % x) == 0: print(n1,"is not a prime number") print(x,"times",n1//x,"is",num) break else: print(n1,"is a prime number") # if input number is smaller than # or equal to the value 1, then it is not prime number else: print(n1,"is not a prime number") Output: 409 is a prime number
Q55. Write Python code to check the given sequence is a palindrome or not?
Answer:
# Python code to check a given sequence # is palindrome or not my_string1 = 'MOM' My_string1 = my_string1.casefold() # reverse the given string rev_string1 = reversed(my_string1) # check whether the string is equal to the reverse of it or not if list(my_string1) == list(rev_string1): print("It is a palindrome") else: print("It is not a palindrome") Output: it is a palindrome
Q56. Write Python code to sort a numerical dataset?
Answer:The code to sort a numerical dataset is as follows:
list = [ "13", "16", "1", "5" , "8"]
list = [int(x) for x in the list]
list.sort()
print(list)
Output:
1, 5, 8, 13, 16
Q57. What is the output of the following code?
x = ['ab','cd']
print(list(map(list, x)))
Answer:The output of the following code is
[ [‘a’, ‘b’], [‘c’, ‘d’]
Q58. What is the procedure to install Python on Windows and set path variable?
Answer: We need to implement the following steps to install Python on Windows, and they are:
After installing Python on your PC, find the place where it is located in your PC using the cmd python command. :
Then visit advanced system settings on your PC and add new variable. Name the new variable as PYTHON_NAME then copy the path and paste it. :
Search for the path variable and select one of the values for it and click on ‘edit’. :
Finally we need to add a semicolon at the end of the value and if the semicolon is not present then type %PYTHON_NAME%.:
Q59. Differentiate between SciPy and NumPy?
Answer:The difference between SciPy and NumPy is as follows:
- NumPy
- Numerical Python is called NumPy
- It is used for performing general and efficient computations on numerical data which is saved in arrays. For example indexing, reshaping, sorting, and so on
- There are some of the linear algebraic functions present in this module but they are not fully fledged. NumPy
- Scientific Python is called SciPy
- This is an entire collection of tools in Python mainly used to perform operations like differentiation, integration and many more.
- For performing algebraic computations this module contain some of the fully fledged operations
Q60. How do Python arrays and lists differ from each other?
Answer:
- Arrays
- Array is defined as a linear structure that is used to store only homogeneous data.
- Since array stores only similar type of data so it occupies less amount of memory when compared to list.
- Length of the array is fixed at the time of designing and no more elements can be added in the middle. Lists
- List are used to store arbitrary and heterogenous data
- List stores different types of data so it requires huge amount of memory
- Length of the list is no fixed, and adding items in the middle is possible in lists.
Q61. Can we make multi-line comments in Python?
Answer:: In python there is no specific syntax to display multi-line comments like other languages. In order to display mitli-line comments in Python, programmers use triple-quoted (docstrings) strings. If the docstring is not used as the first statement in the present method, it will not be considered by Python parser.
Q62. How can Python be an interpreted language?
Answer: As in Python the code which we write is not machine-level code before runtime so, this is the reason why Python is called as an interpreted language.
Q64. List the features of Django?
Answer:Excellent documentation
Python web framework
SEO optimised
High scalability
Versatile in nature
Offers high security
Thoroughly tested
Provides rapid Development
Q65. Which level framework does Django belong to?
Answer: Django is a high-level Python web framework which was developed for realistic design, clean, rapid development.
Q66. What are the advantages of Django?
Answer:One of the important advantages of Django is it is a framework of python
language which is very simple to learn
Django is a multifaceted framework
When it comes to security Django is the best framework
Scalability is added advantage of Django
Q67. Why should we use Django framework?
Answer: The main goal to design Django is to make it simple to its users, to do this Django uses:
The principles concerning rapid development, which implies developers can complete more than one iteration at a time without beginning the full schedule from scratch;
DRY philosophy — Do not Replicate Yourself — that means developers can reuse surviving code and also focus on the individual one.
Q68. List the common security issues that can be avoided by using Django?
Answer: Few common security issues that can be avoided by using Django are:
Clickjacking
Cross-site scripting and
SQL injection
Q69. List a few of the famous companies that are using Django?
Answer: Few well-known companies that are using the Django framework are
Instagram
Spotify
Mozilla
Dropbox
NASA
Q70. What can we do with the Django framework?
Answer:Here is an exciting reality: Django has first created to power a web application as a newspaper publisher, the Lawrence Journal-World. You all can demand it to be very good about handling projects by volumes from the text files, media, including extremely high traffic or else something that operates as a web publication.
Q71. List steps for setting up static files in Django?
Answer:There are only three main steps for setting up Django static files
Firstly set STATIC_ROOT in settings.py
Run manage.py collect static
Setting up a static file entry pythonAnywhere tab
Q72. Is Django stable?
Answer: Yes, Django is used by many famous companies because it is quite stable.
Q73. Differentiate Django reusability code with other frameworks?
Answer:Django web framework is operated and also maintained by an autonomous and non-profit organization designated as Django Software Foundation (DSF). The initial foundation goal is to promote, support, and advance this Django Web framework.
Q74. How can we handle URLs in Django?
Answer: from django.contrib import admin
from django.urls import path
urlpatterns = [
path('appmajix/', appmajix.site.urls),
]
Q75Q. List the mandatory files if Django project?
Answer: manage.py
settings.py
__init__.py
urls.py
wsgi.py
Q76. Explain about Django session?
Answer:A session comprises a mechanism to store information on specific server-side at the interaction by the web application. By default, session reserves in the database and allows file-based and cache-based sessions.
Q77. Why do we use a cookie in Django?
Answer:A cookie is a piece of information that is stored in a client browser for a specific time. When the specific time is completed cookie gets automatically removed from the client browser.
Q78. What are the functions in Python?
Answer:In Python, functions are defined as a block of code that is executable only when it is called. The def keyword is used to define a function in Python.
Q79. What is the use of Django-admin.py?
Answer: Django-admin.py is a command-line argument which is utilised for administrative tasks
Q80. What is the use of manage.py?
Answer: It is an automatically built file inside each Django project. It is a flat wrapper encompassing the Django-admin.py. It possesses the following usage:
It establishes your project's package on sys.path.
It fixes the DJANGO_SETTING_MODULE environment variable to point to your project's setting.py file.
Q81. Why is Django loosely packed?
Answer: Django has described as a loosely coupled framework because concerning the MTV architecture it’s based upon. Django’s architecture means a variant of MVC architecture and also MTV is helpful because this completely separates the server code of the client’s machine.
Q82. List the ways we add view functions to urls.py?
Answer: Adding a function view
Adding a class-based view
Q83. Explain how can we build or set up the database in Django?
Answer:we can make use of edit mysite/setting.py command, it is a simple Python module consists of levels for presenting or displaying Django settings.
By default Django uses SQLite; this also makes easy for Django users in case of any other type of installations. For example, if your database choice is different then you need to follow certain keys in the DATABASE like default items to match database connection settings.
Engines: By these engines you change the database by using commands such as ‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.sqlite3’, ‘django.db.backends.oracle’, ‘django.db.backends.mysql’, and so on.
Name: This represents the name of your own database. If you are familiar with using SQLite as your database, in such case database is available as a file on your particular system. Moreover, the name should be as a fully absolute or exact path along with the file name of the particular file.
Suppose if we are not using SQlite as your database then additional settings such password, user, the host must be added.
Q84. List out the inheritance styles in Django?
Answer: There are three possible inheritance styles in Django, and they are:
Proxy models: This style is mainly used for those who want to modify the Python level behaviour of the model, without modifying the model’s fields.
Abstract Base Classes: This inheritance style is used only when we want to make parent class hold the data which they don’t want to repeat it again in the child class.
Multi-table Inheritance: This inheritance style is used only when we want to subclass an existing model and there must a database table designed for each model on its own.
Q85. How to save an image locally using Python in which we already know the URL address?
Answer: The following code is used to save the image locally from the URL address which we know.
import urllib.request
urllib.request.urlretrieve("URL", "local-filename.jpg")
Q86. How can we access sessions in flask?
Answer:A session will basically allow us to remember information from one request to another. In a flask, a signed cookie is used to make the user look at the session contents and modify them. Moreover, the user can change the session only when the secret key named Flask.secret_key is present.
Q87. How can I practice code?
Answer:There are many online coding sites and platforms exclusively for practice purpose. According to me the Ideal way of learning is by picking up a problem statement and working on it to build your confidence levels. In StackOverflow website, we can see 100 software developers posting their problems.
Q88. What are the database connections in Python Flask, explain?
Answer: Database powered applications are supported by flask. The relational database systems need to create a schema that requires piping the schema.sql file into a SQLite3 command. So, in this case you need to install SQLite3 command on your system to initiate and create the database in the flask.
We can request a database using flask in three ways, and they are:
before_request(): Using this we can request database before only without passing arguments.
after_request(): This method is called after requesting the database and also send the response to client.
teardown_request(): This method is called in the cases where the responses are not guaranteed and the exception is raised. They have no access to modify the request.
Q89. Explain the procedure to minimize or lower the outages of Memcached server in your Python development?
Answer:The following are the steps used to minimize the outages of the Memcached server in your Python development, and they are.
When a single instance fails, this will impact on larger load of the database server. The client makes the request when the data is reloaded. In order to avoid this, the code that you have written must be used to lower cache stampedes then it will used to leave a minimal impact.
The other way is to bring out the instance of the memcached on a new machine by using the IP address of the lost machine.
Another important option is to lower the server outages is code. This code provides you the liberty to modify the memcached server list with minimal work
Another way is by setting timeout value that will be one of the options for memcac
Class Student:
def __init__(self, name):
self.name = name
S1=Student("XYZ")
print(S1.name)
hed clients to implement the memcached server outage. When the performance of the server goes down, the client keeps on sending a request until the timeout limit is reached.
Q90. What is Dogpile effect?
Answer: This is defined as an occurrence of event when the cache expires and also when the websites are hit with more number of requests by the client at a time. This dogpile effect can be averted by the use of a semaphore lock. If in the particular system the value expires then, first of all, the particular process receives the lock and begin generating new value.
Q91. What are the OOPS concepts available in Python?
Answer: Python is also object-oriented programming language like other programming languages. It also contains different OOPS concepts, and they are
Object
Class
Method
Encapsulation
Abstraction
Inheritance
Polymorphism
Q92. Define object in Python?
Answer: An object in Python is defined as an instance that has both state and behaviour. Everything in Python is made of objects.
Q93. What is a class in Python?
Answer:Class is defined as a logical entity that is a huge collection of objects and it also contains both methods and attributes.
Q94. How to create a class in Python?
Answer:In Python programming, the class is created using a class keyword. The syntax for creating a class is as follows:
class ClassName:
#code (statement-suite)
Example of creating a class in Python.
Output:
XYZ
Q95. What is the syntax for creating an instance of a class in Python?
Answer:The syntax for creating an instance of a class is as follows: Answer:The Method is defined as the function associated with a particular object. The method which we define should not be unique as a class instance. Any type of objects can have methods. Answer:Multiple inheritance is supported in python. It is a process that provides flexibility to inherit multiple base classes in a child class. Answer: In simple words, abstraction can be defined as hiding of unnecessary data and showing or executing necessary data. In technical terms, abstraction can be defined as hiding internal process and showing only the functionality. In Python abstraction can be achieved using encapsulation. Answer: Encapsulation is one of the most important aspects of object-oriented programming. Binding or wrapping of code and data together into a single cell is called encapsulation. Encapsulation in Python is mainly used to restrict access to methods and variables. Answer:By using polymorphism in Python we will understand how to perform a single task in different ways. For example, designing a shape is the task and various possible ways in shapes are a triangle, rectangle, circle, and so on. Answer:provide a way to access an instance variable. Python introduced a concept of prefixing the name of the method, function, or variable by using a double or single underscore to act like the behaviour of private and protected access specifiers. Answer:Empty class in Python is defined as a class that does not contain any code defined within the block. It can be created using pass keyword and object to this class can be created outside the class itself.
Q96. Define what is “Method” in Python programming?
Q97. Does multiple inheritances is supported in Python?
Example of multiple inheritance in Python is as follows:
class Calculus:
def Sum(self,a,b):
return a+b;
class Calculus1:
def Mul(self,a,b):
return a*b;
class Derived(Calculus,Calculus1):
def Div(self,a,b):
return a/b;
d = Derived()
print(d.Sum(10,30))
print(d.Mul(10,30))
print(d.Div(10,30))
Output:
40
300
0.3333Q98. What is data abstraction in Python?
Q99. Define encapsulation in Python?
Q100. What is polymorphism in Python?
Q101. Does Python make use of access specifiers
Q102. How can we create an empty class in Python?
Related Articles refer here:
You may also like
Top Python Development Trends in 2023
Python Programming which is currently a trending programming language in the era of information technology, This general purpose programming language is not a newly developed programming instead it has been developed in the year 1991 by Guido Van Rossum. The …