We will go through some of the most asked Python Interview questions to successfully get you through your interview.
Python is the most demanded language in the programming world. Prior promising versions of Python are the reason for immeasurable growth in further development. With the rapid growth, interviewees are nervous about what to learn? What will be asked in the interview? How to answer?
Python has released new features in python 3.9 in 2020. We will also cover questions from the new features because the interviewer does tend to keep tabs and are impressed with the updated candidate.
Here are few conceptual questions:
Table of Contents
q.1 What is the difference between dictionary, list, and tuples?
Lists and tuples are an ordered collection of things, a dictionary is unordered. list and dictionary can be edited while tuple cannot be edited. Dictionary is considered like an associated array in PHP and an object in JavaScript.
You can declare them like:
Lists =[1,2,”hey ”, 29.7]
Tuple=(2,5, “code”, 122.1)
Dictionary={“name”:”RFS”,”rollno”:44}
q.2 What does merge and update operators do?
Merge(|) and update(|=) operators have been recently introduced in early 2020. These operators make it easier to merge or update two or more collections.
Consider,
d1 = { "name ": "Jona", "age ":38 }
d2 = { " name": "Jety", "age": 15, "profession":"doctor" }
d3 |= d2
print(d3)
similarly, update (|=) is equal to d1=d1|d2
q.3 What is the difference between single and double quotes?
In Python, there is no dominant difference between single ad double-quotes. However, you can use single quotes inside double quotes to escape character and vise versa.
Here is a detailed description of coding examples.
https://www.codeleaks.io/single-and-double-quotes-in-python/
q.4 What are the loops in python?
Loops in python are a way to iterate through lists, arrays, tuples, and different collections by writing the code only once. Loops are used where there is a repetition of a task.
Python supports a while and for loop, which is more like a for-each loop.
Here is a detailed description of coding examples.
https://www.codeleaks.io/for-loop-with-mu…riable-in-python/
q.5 What is zoneinfo and what does it do?
Zoneinfo is a Python module that provides a time zone. By default, t uses the systems’ time zone data but if not available it will use data in PyPI.
from zoneinfo import ZoneInfo
from datetime import datetime, timedelta
dt = datetime(2020, 1, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))
print(dt)
q.6 What is pprint?
Pprint is what’s known as pretty-print. It formats data into a much cleaner and readable manner. Image having tons of data incoming and you need to view it. Pretty print makes sure that the data is in a human-understandable format.
q.7 What is the difference between a function, method, and module?
In other programming languages, there is no difference in a function and a method. However, python clearly states and utilize the difference between them. A function is independent and can be called with its name. while a method is dependent on an object and needs its reference to be invoked.
On the other hand, the module is an independent piece of code that can be imported and called upon. But all the functionality must be called with the reference of the module name after importing it in another environment.
Here are a few articles with details and code examples.
https://www.codeleaks.io/function-vs-method-in-python/
https://www.codeleaks.io/function-vs-module-in-python/
q.8 What is pep 8?
Python Enhancement Proposal is a set of rules that specify how to format the code for maximum readability.
q.9 What is a switch case and how can we implement it in python?
Switch-case is an alternative of if-else. You can switch to the matching possibility and jump to the associated code and execute it. Python does not support the switch case. However, it can be implemented through a dictionary.
q.10 What is Tkinter?
Tkinter is python’s GUI module, which allows output to be displayed in a graphical user interface rather than the traditional console or terminal. you can include tkinter module in your python application by importing it.
q.11 What is slicing?
Slicing is a built-in function that fetches the part of the string with the mentioned range of index.
Str=”codeleaks!”
print(slice(0,4))
you can also mention the step size in the third parameter.
q.12 How can you generate random numbers in python?
Python has a library of random. You can import it and call a function to generate random integers.
import random
num = random.randint(0,10)
print(num)
you will be able to see random numbers from 1 till 9.
q.13 What are the modules and packages in Python?
In a package, there are multiple modules whereas a module is a file consisting of classes, functions, and attributes.
To make it simple, a package is a collection of modules and a module is a file of collection of classes, functions, etc.
q.14 How is memory managed in Python?
Python uses Heap for memory Management, this space is not accessible to the programmer. Therefore, the interpreter acts as a source of interaction between them.
The objects are mapped into the heap and stored by the memory manager. Though, some tools are accessible to the programmer to execute commands.
Python also has an inbuilt garbage collector, which recycles all the unused memory and so that it can be made available.
q.15 What types do python support?
The common data types such as int, float, decimal, bool, string, tuple, and range. And some mutable data types are list, dictionary, set, and user-defined classes.
q.16 What is Pychecker and Pylint?
Pychecker is an aiding tool to analyze bugs in the source code. Like a compiler, it catches errors in the code and alerts the programmer.
Pylint is another analytical tool that checks the quality of code, errors and follows pep8 recommended styles.
q.17 What type of language is python?
Interpreted, high-level, general-purpose programming language.
Python is widely used for different purposes like gaming, web applications, desktop applications, and scripting, etc.
q.18 Is Python an interpreted language? If so explain how?
Yes! Python is an interpreted language because the python code instructions are executed directly without having to compile it into machine code first.
q.19 What are virtualenvs?
Virtualenvs are used to make sure that isolation is utilized in the project. It creates a wrapper of the project’s own libraries and dependencies. By using pip, the hosting developing and deploying can be done easily without having other projects or utilities involving.
q.20 What is the namespace in Python?
Namespace is a way to make sure the variable defined is unique within the scope of a namespace. This avoids conflicts.
q.21 What are local variables and global variables in Python?
Variables accessible to any other class or function is a global variable. Globally accessible. These variables are defined outside of a function.
Local variables are those that are only accessible in a certain scope. Functions have local variables defined inside them.
q.22 Explain what is Flask & its benefits?
Flask is a Python web framework. Flask allows you to develop web applications with the help of tools, libraries, and technologies.
Flask is beneficial because it has integrated support for unit testing, built-in server and fast debugger, Unicode base, support for cookies, and templating jinja2. Furthermore, its highly flexible, HTTP request handling is easier and faster to develop.
q.23 what is the difference between Django, Pyramid, and Flask?
Django, Pyramid and Flask are all frameworks of Python. Flask is a micro framework while Django and pyramid deals with large projects.
Pyramid is more flexible in terms of providing the developer with more choice in the database, structure of URL, templates, etc.
q.24 Explain what is Dogpile effect? How can you prevent this effect?
Dogpile effect occurs when the cache expires and the server has overloaded requests from the user. Dogpile effect can be avoided through semaphore lock. Semaphore prevents deadlocks in the application and allocates services.
q.25 Is python a case sensitive language?
Python is a case sensitive language. Meaning if you named a function, attribute, or class in upper, lower, or camel case, then you will have to call it by that case strictly.
q.26 What are sets? What’s the difference between sets and tuples?
Sets are unordered collection which has no duplicated elements. Tuples cannot be edited later after being declared.
myset = set(["a", "b", "c","c"])
print(myset)
q.27 What is PYTHON PATH?
When modules are imported, the interpreter searches directories from where the module is loaded. These paths are defined to direct the interpreter to the module.
q.28 What is lambda in Python? Why is it used?
Lambda is used when an anonymous function is required for a short period. It can have as many arguments as it can and can even have functions as arguments but can only have one expression.
x = lambda a : a + 10
print(x(5))
q.29 What is the purpose of ** operator?
a=2
b=4
print(a**b)
output: 16
q.30 What is pickling and unpickling?
Pickle module takes any Python object and converts it into a string representation and dumps it into a file through the dump function. While fetching the original Python objects from the stored value is unpickling.
q.31 What can you do to copy an object?
You can try copy.copy () or copy.deepcopy() for the general case. Though, you cannot copy all objects but most of them.
q.32 What does pass operation do?
No operation should be done. If a pass statement is written, then it means there won’t be any further operations.
q.32 Can we use terminator?
Yes, we can use terminator as it is been supported by the previous python version. But spaces are used to determine the flow of execution and termination in new versions of python.
q.33 What is the difference between .py and .pyc files?
The .py files are python files having the source code whereas .pyc has the bytecode of your program.
Q.34 what is cython?
Cython is a programming language for C and python. Compiling both python and C language to create a harmonious environment for both.
Find the output
Q.35 What will be the output of the following code?
j=0
while j <5:
print(j)
j+=1
if j ==4:
break
else:
print(“ “)
OUTPUT: 0 1 2 3
Q.36 What will be the output of the following code?
x = "code leaks"
i = "u"
while i in x:
print(i, end=" ")
OUTPUT: nothing, because i is not in x
Q.37 What will be the output of the following code?
print('my_string'.isidentifier())
OUTPUT: True, it’s a valid identifier.
Q.38 What will be the output of the following code?
str1="hello"
c=0
for x in str1:
if(x!="l"):
c=c+1
else:
pass
print(c)
Q.39 Which of the following Python code will give different output from the others?
A. for i in range(0,5):
print(i)
B. for j in [0,1,2,3,4]:
print(j)
C. for k in [0,1,2,3,4,5]:
print(k)
D. for l in range(0,5,1):
print(l)
OUTPUT: C, no other option has all values from 0 to 5.
Q.40 What will be the output of the following code?
x = 12
for i in x:
print(i)
OUTPUT: error! Type int are not iterable.
Q.41 What is the output of print tuple * 2 if tuple = (1, 'me')?
OUTPUT: Two times of (1, me) will be printed.
Q.42 write the commands to delete a file in python
import os
os.remove("File.txt")
print("File Removed!")
Q.43 Which statement is false for __init__?
A) __init__ is called manually on object creation.
B) __init__ is a constructor method in Python.
C) All classes have an __init__ method associated with them.
D) __init__ allocates memory for objects.
OUTPUT: because the calling is dynamically with the object creation.
Q.44 Write a NumPy program to evaluate Einstein’s summation convention of two given multidimensional arrays.
import numpy as np
mat1 = np.array([9,0,4])
mat2 = np.array([3,2,5])
print("1-d arrays:")
print(mat1)
print(mat2)
result = np.einsum("n,n", mat1, mat2)
print("Einstein’s summation convention of arrays:")
print(result)
x = np.arange(9).reshape(3, 3)
y = np.arange(3, 12).reshape(3, 3)
print("Original Higher dimension:")
print(x)
print(y)
result = np.einsum("mk,kn", x, y)
print("Einstein’s summation convention of the said arrays:")
print(result)

Q.45 Write a NumPy program to find a matrix or vector norm.
import numpy as np
vector = np.arange(8)
result = np.linalg.norm(vector)
print("Vector norm:")
print(result)
mul = np.matrix('1, 2; 3, 4')
result1 = np.linalg.norm(mul)
print("Matrix norm:")
print(result1)

Q.46 Write a NumPy program to compute the condition number of a given matrix.
import numpy as np
m = np.array([[1,2],[3,4]])
print("Original matrix:")
print(m)
result = np.linalg.cond(m)
print("Condition number of the said matrix:")
print(result)

Q.47 Write a Python program to generate the running product of the elements of a given iterable.
from itertools import accumulate
import operator
def running_product(it):
return accumulate(it,operator.mul)
#List
result = running_product([1,2,3,4,5,6,7])
print("multiples of list:")
for i in result:
print(i)
#Tuple
result = running_product((1,2,3,4,5,6,7))
print("multiples of Tuple:")
for i in result:
print(i)

Q.48 Write a Python program to interleave two given list into another list randomly using map() function.
import random
def randomly_interleave(nums1, nums2):
result = list(map(next, random.sample([iter(nums1)]*len(nums1) + [iter(nums2)]*len(nums2), len(nums1)+len(nums2))))
return result
nums1 = [1,5,2,1,8]
nums2 = [4,9,12,3,1,11]
print("Original lists:")
print(nums1)
print(nums2)
print("\nInterleave two given list into another list randomly:")
print(randomly_interleave(nums1, nums2))

Q.49 Write a Python code to check the status code issued by a server in response to a client’s request made to the server.
import requests
res = requests.get('https://google.com/')
print("Response of https://google.com/:")
print(res.status_code)
res = requests.get('https://amazon.com/')
print("Response of https://amazon.com/:")
print(res.status_code)
res = requests.get('https://www.codeleaks.io/')
print("Response of https://www.codeleaks.io/:")
print(res.status_code)
print("\nMethods and attributes available \nrequest of https://www.codeleaks.io/:\n")
print(dir(res))

Q 50. Write a Python program to extract year, month and date from an url.
import re
def extract_date(url):
return re.findall(r'/(\d{4})/(\d{1,2})/(\d{1,2})/', url)
urlResult= "https://www.washingtonpost.com/news/football-insider/wp/2016/09/02/odell-beckhams-fame-rests-on-one-stupid-little-ball-josh-norman-tells-author/"
print(extract_date(urlResult))