Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

52 Python Question Answers

src: https://youtu.be/YeupGcOW-3k

Uploaded by

Haibara Ai
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

52 Python Question Answers

src: https://youtu.be/YeupGcOW-3k

Uploaded by

Haibara Ai
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 71

52 Python Developer

Interview Questions-
Answers
Watch Full Video On Youtube:
https://youtu.be/YeupGcO
W-3k

Connect with me:


Youtube: https://www.youtube.com/c/nitmantalks
Instagram: https://www.instagram.com/nitinmangotra/
LinkedIn:
https://www.linkedin.com/in/nitin-mangotra-9a075a149/
Facebook: https://www.facebook.com/NitManTalks/
Twitter: https://twitter.com/nitinmangotra07/
Telegram: https://t.me/nitmantalks/
1.Difference Between List and Tuple

LIST Tuple
1. Lists are mutable 1. Tuples are immutable
2. List is a container to contain different types of 2. Tuple is also similar to list but contains immutable
objects and is used to iterate objects. objects.
3. Syntax Of List
3. Syntax Of Tuple
list = ['a', 'b', 'c', 1,2,3]
tuples = ('a', 'b', 'c', 1, 2)
4. List iteration is slower
5. Lists consume more memory 4. Tuple processing is faster than List.
6. Operations like insertion and deletion are better 5. Tuple consume less memory
performed. 6. Elements can be accessed better.
Decorator Coding Example

2. What is def decorator_func(func):


def wrapper_func():
Decorator? Worked")
print("wrapper_func

Explain With
A Decorator is just a function that
return func()
print("decorator_func worked")

Example.
takes another function as an
return wrapper_func

argument, add some kind of def show():


print("Show Worked")
functionality and then returns decorator_show = decorator_func(show)
another function. decorator_show()
All of this without altering the
source code of the original function #Alternative
that you passed in. @decorator_func
def display():
print('display
worked') Output:
display()
decorator_func worked
wrapper_func Worked
Show Worked
decorator_func worked
wrapper_func Worked
3. Difference Between List and Dict Comprehension

List Comprehension Dict Comprehension


Syntax: Syntax :

[expression for item in iterable if conditional] {key:value for (key,value) in iterable if conditional}

Example: Example:
Common Way: Common Way:
l = [] d = {}
for i in range(10): for i in range(1,10):
if i%2: sqr = i*i
l.append(i) d[i] = i*i
print(l) print(d)

Using List Comprehension: Using Dict Comprehension:


ls = [i for i in range(10) if i%2] d1={n:n*n for n in range(1,10)}
print(ls) print (d1)

Output: Output:
[1, 3, 5, 7, 9] {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
4. How Memory Managed In Python?

❏ Memory management in Python involves a private heap containing all Python objects and data structures.
Interpreter takes care of Python heap and that the programmer has no access to it.
❏ The allocation of heap space for Python objects is done by Python memory manager. The core API of
Python provides some tools for the programmer to code reliable and more robust program.
❏ Python also has a build-in garbage collector which recycles all the unused memory. When an object is no
longer referenced by the program, the heap space it occupies can be freed. The garbage collector determines
objects which are no longer referenced by the program frees the occupied memory and make it available to
the heap space.
❏ The gc module defines functions to enable /disable garbage collector:

- gc.enable() -Enables automatic garbage collection.


- gc.disable() - Disables automatic garbage collection.

Source: https://www.careerride.com/python-memory-management.aspx
5. Difference Between Generators And Iterators

GENERATOR ITERATOR
● Generators are iterators which can execute only once. ● An iterator is an object which contains a countable number
● Generator uses “yield” keyword. of values and it is used to iterate over iterable objects like
● Generators are mostly used in loops to generate an list, tuples, sets, etc.
iterator by returning all the values in the loop without ● Iterators are used mostly to iterate or convert other objects
affecting the iteration of the loop. to an iterator using iter() function.
● Every generator is an iterator. ● Iterator uses iter() and next() functions.
● Every iterator is not a generator.
EXAMPLE:
def sqr(n): Example:
for i in range(1, n+1): iter_list = iter(['A', 'B', 'C'])
yield i*i
print(next(iter_list))
a = sqr(3)
print(next(a))
print(next(iter_list))
print(next(a)) print(next(iter_list))
print(next(a))
Output:
Output: A
1 B
4 C
9
6. What is ‘init’ Keyword In Python?

__init__.py file __init__() function

The __init__ method is similar to constructors in C++


The __init__.py file lets the Python interpreter know that a
and Java. Constructors are used to initialize the
directory contains code for a Python module. It can be object’s state.
blank. Without one, you cannot import modules from
# A Sample class with init method
another folder into your project.
class Person:
# init method or constructor
The role of the __init__.py file is similar to the __init__ def __init__(self, name):
self.name = name
function in a Python class. The file essentially the
constructor of your package or directory without it being # Sample Method
def say_hi(self):
called such. It sets up how packages or functions will be print('Hello, my name is', self.name)
imported into your other files.
p = Person('Nitin')
p.say_hi()
Output:
Hello, my name is Nitin
7. Difference Between Modules and Packages in Python

Module
The module is a simple Python file that contains collections of functions and global variables and with
having a .py extension file. It is an executable file and to organize all the modules we have the concept
called Package in Python.
A module is a single file (or files) that are imported under one import and used. E.g.
import my_module

Package
The package is a simple directory having collections of modules. This directory contains Python modules
and also having __init__.py file by which the interpreter interprets it as a Package. The package is simply
a namespace. The package also contains sub-packages inside it.
A package is a collection of modules in directories that give a package hierarchy.
from my_package.abc import a
8. Difference Between Range and Xrange?

Parameters Range() Xrange()

Return type It returns a list of integers. It returns a generator object.

Memory Consumption Since range() returns a list of elements, it takes In comparison to range(), it takes less memory.
more memory.

Speed Its execution speed is slower. Its execution speed is faster.

Python Version Python 2, Python 3 xrange no longer exists.

Operations Since it returns a list, all kinds of arithmetic Such operations cannot be performed on xrange().
operations can be performed.
9. What are Generators. Explain it with Example.

Example:
● Generators are iterators which can execute only once. def sqr(n):
for i in range(1, n+1):
● Every generator is an iterator. yield i*i
a = sqr(3)
● Generator uses “yield” keyword.
print("The square are : ")
● Generators are mostly used in loops to generate an iterator print(next(a))
print(next(a))
by returning all the values in the loop without affecting the
print(next(a))
iteration of the loop

Output:
The square are :
1
4
9
10. What are in-built Data Types in Python OR
Explain Mutable and Immutable Data Types

A first fundamental distinction that Python makes on data is about whether or not the value of an object changes.
If the value can change, the object is called mutable, while if the value cannot change, the object is called immutable.

DataType Mutable Or Immutable?


Boolean (bool) Immutable

Integer (int) Immutable

Float Immutable

String (str) Immutable

tuple Immutable

frozenset Immutable

list Mutable

set Mutable

dict Mutable
Common Questions

11. Explain Ternary Operator in Python?

The syntax for the Python ternary statement is as follows:

[if_true] if [expression] else [if_false]

Ternary Operator
Example:
age = 25
discount = 5 if age < 65 else
10
print(discount)
12. What is Inheritance In Python

In inheritance, the child class acquires the properties and can class A:
access all the data members and functions defined in the parent def display(self):
class. A child class can also provide its specific implementation to print("A Display")
the functions of the parent class.
class B(A):
def show(self):
In python, a derived class can inherit base class by just mentioning
print("B Show")
the base in the bracket after the derived class name. d = B()
d.show()
Class A(B): d.display()

Output:
B Show
A Display
13. Difference Between Local and Global Variable in
Python
Local Variable Global Variable

It is declared inside a function. It is declared outside the function.

If it is not initialized, a garbage value is stored If it is not initialized zero is stored as default.

It is created when the function starts execution and lost It is created before the program’s global execution starts
and
when the functions terminate.
lost when the program terminates.

Data sharing is not possible as data of the local variable Data sharing is possible as multiple functions can access
can the
be accessed by only one function. same global variable.

Parameters passing is required for local variables to Parameters passing is not necessary for a global variable as
access it
the value in other function is visible throughout the program

When the value of the local variable is modified in one When the value of the global variable is modified in one
function, the changes are not visible in another function. function changes are visible in the rest of the program.

Local variables can be accessed with the help of You can access global variables by any statement in the
statements,
program.
inside a function in which they are declared.

It is stored on the stack unless specified. It is stored on a fixed location decided by the compiler.

Source: https://www.guru99.com/local-vs-global-variable.html
14. Explain Break, Continue and Pass Statement

● A break statement, when used inside the loop, will terminate the loop and exit. If used inside nested loops, it
will break out from the current loop.
● A continue statement will stop the current execution when used inside a loop, and the control will go back to
the start of the loop.
● A pass statement is a null statement. When the Python interpreter comes across the pass statement, it does
nothing and is ignored.

Break Statement Continue Statement Pass Statement


Example Example Example
for i in range(10): for i in range(10): def my_func():
if i == 7: if i == 7: print('pass inside function')
break continue pass
print( i, end = ",") print( i, end = ",") my_func()

Output: Output:
0,1,2,3,4,5,6, 0,1,2,3,4,5,6,8,9, Output:
pass inside function
15. What is 'self' Keyword in python?

The ‘self’ parameter is a reference to the current instance of the class, and is used to access variables
that belongs to the class.

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def info(self):
print(f"My name is {self.name}. I am {self.age} years old.")

c = Person("Nitin",23)
c.info()

Output:
My name is Nitin. I am 23 years old.
16. Difference Between Pickling and Unpickling?

Pickling:
In python, the pickle module accepts any Python object, transforms it into a string representation, and dumps it into a file by
using the dump function. This process is known as pickling. The function used for this process is pickle.dump()

Unpickling:
The process of retrieving the original python object from the stored string representation is called unpickling.
The function used for this process is pickle.load()

- They are inverses of each other.


- Pickling, also called serialization, involves converting a Python object into a series of bytes which can be
written out to a file.
- Unpicking, or de-serialization, does the opposite–it converts a series of bytes into the Python object it
represents.
17. Explain Function of List, Set, Tuple And Dictionary?

Functions Of List Functions Of Tuple


❏ sort(): Sorts the list in ascending order. ❏ cmp(tuple1, tuple2) - Compares elements of both tuples.
❏ append(): Adds a single element to a list. ❏ len(): total length of the tuple.
❏ max(): Returns item from the tuple with max value.
❏ extend(): Adds multiple elements to a list. ❏ min(): Returns item from the tuple with min value.
❏ index(): Returns the first appearance of the specified value. ❏ tuple(seq): Converts a list into tuple.
❏ max(list): It returns an item from the list with max value. ❏ sum(): returns the arithmetic sum of all the items in the tuple.
❏ min(list): It returns an item from the list with min value. ❏ any(): If even one item in the tuple has a Boolean value of True, it returns True. Otherwise,
❏ len(list): It gives the total length of the list. it returns False.
❏ list(seq): Converts a tuple into a list. ❏ all(): returns True only if all items have a Boolean value of True. Otherwise, it returns False.
❏ cmp(list1, list2): It compares elements of both lists list1 and ❏ sorted(): a sorted version of the tuple.
❏ index(): It takes one argument and returns the index of the first appearance of an item in
list2.
❏ a tuple
type(list): It returns the class type of an object. ❏ count(): It takes one argument and returns the number of times an item appears in the
tuple.

Functions Of Dictionary Functions Of Set


❏ add(): Adds an element to the set
❏ clear(): Removes all the elements from the dictionary ❏ clear(): Removes all the elements from the set
❏ copy(): Returns a copy of the dictionary ❏ copy(): Returns a copy of the set
❏ fromkeys(): Returns a dictionary with the specified keys and value ❏ difference(): Returns a set containing the difference between two or more sets
❏ difference_update(): Removes the items in this set that are also included in another, specified set
❏ get(): Returns the value of the specified key ❏ discard(): Remove the specified item
❏ items(): Returns a list containing a tuple for each key value pair ❏ intersection(): Returns a set, that is the intersection of two or more sets
❏ keys(): Returns a list containing the dictionary's keys ❏ intersection_update(): Removes the items in this set that are not present in other, specified set(s)
❏ pop(): Removes the element with the specified key ❏ isdisjoint(): Returns whether two sets have a intersection or not
❏ issubset(): Returns whether another set contains this set or not
❏ popitem(): Removes the last inserted key-value pair ❏ issuperset(): Returns whether this set contains another set or not
❏ setdefault(): Returns the value of the specified key. If the key does not exist: ❏ pop(): Removes an element from the set
insert the key, with the specified value ❏ remove(): Removes the specified element
❏ symmetric_difference(): Returns a set with the symmetric differences of two sets
❏ update(): Updates the dictionary with the specified key-value pairs ❏ symmetric_difference_update(): inserts the symmetric differences from this set and another
❏ values(): Returns a list of all the values in the dictionary ❏ union(): Return a set containing the union of sets
❏ cmp(): compare two dictionaries ❏ update(): Update the set with another set, or any other iterable
17. Explain Function of List, Set, Tuple And Dictionary?

Functions Of List Functions Of Tuple


❏ sort(): Sorts the list in ascending order. ❏ cmp(tuple1, tuple2) - Compares elements of both tuples.
❏ append(): Adds a single element to a list. ❏ len(): total length of the tuple.
❏ ❏ max(): Returns item from the tuple with max value.
extend(): Adds multiple elements to a list.
❏ min(): Returns item from the tuple with min value.
❏ index(): Returns the first appearance of the
❏ tuple(seq): Converts a list into tuple.
specified value. ❏ sum(): returns the arithmetic sum of all the items in the
❏ max(list): It returns an item from the list with tuple.
max value. ❏ any(): If even one item in the tuple has a Boolean value
❏ min(list): It returns an item from the list with of True, it returns True. Otherwise, it returns False.
min value. ❏ all(): returns True only if all items have a Boolean value
❏ len(list): It gives the total length of the list. of True. Otherwise, it returns False.
❏ list(seq): Converts a tuple into a list. ❏ sorted(): a sorted version of the tuple.
❏ cmp(list1, list2): It compares elements of both ❏ index(): It takes one argument and returns the index of
lists list1 and list2. the first appearance of an item in a tuple
❏ count(): It takes one argument and returns the number
❏ type(list): It returns the class type of an object.
of times an item appears in the tuple.
17. Explain Function of List, Set, Tuple And Dictionary?

Functions Of Set
Functions Of Dictionary ❏ add(): Adds an element to the set
❏ clear(): Removes all the elements from the dictionary ❏ clear(): Removes all the elements from the set
❏ copy(): Returns a copy of the dictionary ❏ copy(): Returns a copy of the set
❏ fromkeys(): Returns a dictionary with the specified keys ❏ difference(): Returns a set containing the difference between two or
and value more sets
❏ get(): Returns the value of the specified key ❏ difference_update(): Removes the items in this set that are also
❏ items(): Returns a list containing a tuple for each key included in another, specified set
value pair ❏ discard(): Remove the specified item
❏ keys(): Returns a list containing the dictionary's keys ❏ intersection(): Returns a set, that is the intersection of two or more sets
❏ pop(): Removes the element with the specified key ❏ intersection_update(): Removes the items in this set that are not
❏ popitem(): Removes the last inserted key-value pair present in other, specified set(s)
❏ setdefault(): Returns the value of the specified key. If the ❏ isdisjoint(): Returns whether two sets have a intersection or not
key does not exist: insert the key, with the specified value ❏ issubset(): Returns whether another set contains this set or not
❏ update(): Updates the dictionary with the specified key- ❏ issuperset(): Returns whether this set contains another set or not
value pairs ❏ pop(): Removes an element from the set
❏ values(): Returns a list of all the values in the dictionary ❏ remove(): Removes the specified element
❏ cmp(): compare two dictionaries ❏ symmetric_difference(): Returns a set with the symmetric differences of
two sets
❏ symmetric_difference_update(): inserts the symmetric differences from
this set and another
❏ union(): Return a set containing the union of sets
❏ update(): Update the set with another set, or any other iterable
18. What are Python Iterators?

❖ An iterator is an object which contains a countable number of values and it is used to iterate over iterable
objects like list, tuples, sets, etc.
❖ Iterators are used mostly to iterate or convert other objects to an iterator using iter() function.
❖ Iterator uses iter() and next() functions.
❖ Every iterator is not a generator.

Example:

iter_list = iter(['A', 'B', 'C'])


print(next(iter_list))
print(next(iter_list))
print(next(iter_list))

Output:
A
B
C
19. Explain Type Conversion in Python.
[(int(), float(), ord(), oct(), str() etc.)]

❏ int() - Converts any data type into an integer.


❏ float() - Returns A floating point number from a number or string
❏ oct() - Returns its octal representation in a string format.
❏ hex() - Convert the integer into a suitable hexadecimal form for the number of the integer.
❏ ord() - Returns the integer of the Unicode point of the character in the Unicode case or the byte value in the
case of an 8-bit argument.
❏ chr(number) - Returns the character (string) from the integer (represents unicode code point of the
character).
❏ eval() - Parses the expression argument and evaluates it as a python expression.
❏ str() - Convert a value (integer or float) into a string.
❏ repr() - Returns the string representation of the value passed to eval function by default. For the custom
class object, it returns a string enclosed in angle brackets that contains the name and address of the object
by default.
20. What does *args and **kwargs mean? Expain

When you are not clear how many arguments you need to pass to a particular function, then we use *args and **kwargs.

The *args keyword represents a varied number of arguments. It is used to add together the values of multiple arguments

The **kwargs keyword represents an arbitrary number of arguments that are passed to a function. **kwargs keywords are
stored in a dictionary. You can access each item by referring to the keyword you associated with an argument when you
passed the argument.

*args Python Example: **Kwargs Python Example


def sum(*args): def show(**kwargs):
total = 0 print(kwargs)
for a in args:
total = total + show(A=1,B=2,C=3)
a
print(total)
Output:
sum(1,2,3,4,5) {'A': 1, 'B': 2, 'C': 3}

Output:
15
21. What is "Open" and "With" statement in Python?

- Both Statements are used in case of file handling.


- With the “With” statement, you get better syntax and exceptions handling.

f = open("nitin.txt")
content = f.read()
print(content)
f.close()

with open("nitin.txt") as f:
content = f.read()
print(content)
22. Different Ways To Read And Write In A File In Python?

Syntax of Python open file function:

file_object = open("filename", "mode")


❏ Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file. If the file does not exists, raises I/O
error. This is also the default mode in which file is opened.
❏ Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the
file does not exists.
❏ Write Only (‘w’) : Open the file for writing. For existing file, the data is truncated and over-written. The handle is positioned at the
beginning of the file. Creates the file if the file does not exists
❏ Write and Read (‘w+’) : Open the file for reading and writing. For existing file, data is truncated and over-written. The handle is
positioned at the beginning of the file.
❏ Append Only (‘a’) : Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The
data being written will be inserted at the end, after the existing data.
❏ Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the
end of the file. The data being written will be inserted at the end, after the existing data.
❏ Text mode (‘t’): meaning \n characters will be translated to the host OS line endings when writing to a file, and back again when
reading.
❏ Exclusive creation (‘x’): File is created and opened for writing – but only if it doesn't already exist. Otherwise you get a FileExistsError.
❏ Binary mode (‘b’): appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'.
23. What is Pythonpath?

PYTHONPATH is an environment variable which you can set to add additional directories where
python will look for modules and packages

The ‘PYTHONPATH’ variable holds a string with the name of various directories that need to be
added to the sys.path directory list by Python.

The primary use of this variable is to allow users to import modules that are not made installable
yet.
24. How Exception Handled In Python?

Try: This block will test the exceptional error try:


to occur. # Some Code....!

Except: Here you can handle the error. except:


# Optional Block
Else: If there is no exception then this block # Handling of exception (if required)
will be executed.
else:
# Some code .....
Finally: Finally block always gets executed
# execute if no exception
either exception is generated or not.
finally:
# Some code .....(always executed)
25. Difference Between Python 2.0 & Python 3.0

Basis of comparison Python 3 Python 2

Syntax def main(): def main():


print("Hello World!") print "Hello World!"
if __name__== "__main__":
if __name__== "__main__":
main()
main()

Release Date 2008 2000

Function print print (“hello”) print “hello”

Division of Integers Whenever two integers are divided, you get a float When two integers are divided, you always provide integer
value value.

Unicode In Python 3, default storing of strings is Unicode. To store Unicode string value, you require to define them with
“u”.

Syntax The syntax is simpler and easily understandable. The syntax of Python 2 was comparatively difficult to
understand.

https://www.guru99.com/python-2-vs-python-3.html
25. Difference Between Python 2.0 & Python 3.0

Basis of comparison Python 3 Python 2

Rules of ordering In this version, Rules of ordering comparisons have been Rules of ordering comparison are very complex.
Comparisons simplified.

Iteration The new Range() function introduced to perform In Python 2, the xrange() is used for iterations.
iterations.

Exceptions It should be enclosed in parenthesis. It should be enclosed in notations.

Leak of variables The value of variables never changes. The value of the global variable will change while
using
it inside for-loop.

Backward Not difficult to port python 2 to python 3 but it is never Python version 3 is not backwardly compatible with
compatibility reliable. Python 2.

Library Many recent developers are creating libraries which you Many older libraries created for Python 2 is not
can
forward-compatible.
only use with Python 3.

https://www.guru99.com/python-2-vs-python-3.html
26. What is ‘PIP’ In Python

Python pip is the package manager for Python packages. We can use pip to install packages that do
not come with Python.

The basic syntax of pip commands in command prompt is:

pip 'arguments'

Pip install <package_name>


27. Where Python Is Used?

❏ Web Applications
❏ Desktop Applications
❏ Database Applications
❏ Networking Application
❏ Machine Learning
❏ Artificial Intelligence
❏ Data Analysis
❏ IOT Applications
❏ Games and many more…!
28. How to use F String and Format or Replacement Operator?

#How To Use f-string


name = 'Nitin'
role = 'Python Developer'
print(f"Hello, My name is {name} and I'm {role}")

Output:
Hello, My name is Nitin and I'm Python Developer

#How To Use format Operator


name = 'Nitin'
role = 'Python Developer'
print(("Hello, My name is {} and I'm
{}").format(name,role))

Output:
Hello, My name is Nitin and I'm Python Developer
29. How to Get List of all keys in a Dictionary?

Using List: Using Keys() Function:


dct = {'A': 1, 'B': 2, 'C': 3} d = {'A': 1, 'B': 2, 'C': 3}
all_keys = list(dct.keys()) x = d.keys()
print(all_keys) # ['A', 'B', 'C'] print([k for k in x])

Shortcut for Above Code:


Using Iterable Unpacking
dct = {'A': 1, 'B': 2, 'C': 3}
all_keys = list(dct) Operator:
print(all_keys) # ['A', 'B', 'C'] d = {'A': 1, 'B': 2, 'C': 3}
*x, = d.keys()
print(x)
Using Iterable Unpacking
Operator: Shortcut For Above Code:
d = {'A': 1, 'B': 2, 'C': 3} d = {'A': 1, 'B': 2, 'C': 3}
x = [*d.keys()] *x, = d
print(x) print(x)

Shortcut For Above Code: Output Is Same In All 7 Cases:


d = {'A': 1, 'B': 2, 'C': 3} ['A', 'B', 'C']
x = [*d]
print(x)
30. Difference Between Abstraction and Encapsulation.

Abstraction Encapsulation

Abstraction works on the design level. Encapsulation works on the application level.

Abstraction is implemented to hide unnecessary data and Encapsulation is the mechanism of hiding the code and the data
withdrawing
together from the outside world or misuse.
relevant data.

It highlights what the work of an object instead of how the object It focuses on the inner details of how the object works. Modifications
works is can be done later to the settings.

Abstraction focuses on outside viewing, for example, shifting the car. Encapsulation focuses on internal working or inner viewing, for
example, the production of the car.

Abstraction is supported in Java with the interface and the abstract Encapsulation is supported using, e.g. public, private and secure
class. access modification systems.

In a nutshell, abstraction is hiding implementation with the help of In a nutshell, encapsulation is hiding the data with the help of
an getters
interface and an abstract class. and setters.

https://www.educba.com/abstraction-vs-encapsulation/
Tricky Questions

31. Does Python Support Multiple Inheritance. (Diamond Problem)

Yes, Python Supports Multiple Inheritance.

class A
What Is Diamond {
Problem? public void display()
{
What Java does not allow is multiple System.out.println("class A");
inheritance where one class can }
}
inherit properties from more than one
class. It is known as the diamond
problem. //not supported in Java
class C extends A public class D extends B,C
class B extends A
{
{ {
public static void main(String args[])
@Override @Override {
public void display() public void display() D d = new D();
{ { //creates ambiguity which display() method to call
System.out.println("class B"); System.out.println("class C"); d.display();
} } }
} } }

In the above figure, we find that class D is trying to inherit form class B and class C, that is not allowed in Java.
31. Does Python Support Multiple Inheritance. (Diamond Problem)

Multiple Inheritance In Output:


Python: b
class A:
def abc(self):
print("a")

class B(A):
def abc(self):
print("b")

class C(A):
def abc(self):
print("c")

class D(B,C):
pass

d = D()
d.abc()
32. How to initialize Empty List, Tuple, Dict and Set?

Empty List:
a = []

Empty Tuple:
a = ()

Empty Dict:
a = {}

Empty Set:
a = set()
33. Difference Between .py and .pyc

❏ .py files contain the source code of a program. Whereas, .pyc file contains the bytecode of your
program.
❏ Python compiles the .py files and saves it as .pyc files , so it can reference them in subsequent
invocations.
❏ The .pyc contain the compiled bytecode of Python source files. This code is then executed by
Python's virtual machine .
34. How Slicing Works In String Manipulation. Explain.

Syntax:
Str_Object[Start_Position:End_Position:Step]

s = 'HelloWorld'

Indexing:

H E L L O W O R L D

0 1 2 3 4 5 6 7 8 9
-10

-9 -8 -7 -6 -5 -4 -3 -2 -1
print(s[:])

Output:
HelloWorld
34. How Slicing Works In String Manipulation. Explain.

Syntax:
Str_Object[Start_Position:End_Position:Step]

s = 'HelloWorld'

Indexing:

H E L L O W O R L D

0 1 2 3 4 5 6 7 8 9
-10

-9 -8 -7 -6 -5 -4 -3 -2 -1
print(s[::])

Output:
HelloWorld
34. How Slicing Works In String Manipulation. Explain.

Syntax:
Str_Object[Start_Position:End_Position:Step]

s = 'HelloWorld'

Indexing:

H E L L O W O R L D

0 1 2 3 4 5 6 7 8 9
-10

-9 -8 -7 -6 -5 -4 -3 -2 -1
print(s[:5])

Output:
Hello
34. How Slicing Works In String Manipulation. Explain.

Syntax:
Str_Object[Start_Position:End_Position:Step]

s = 'HelloWorld'

Indexing:

H E L L O W O R L D

0 1 2 3 4 5 6 7 8 9
-10

-9 -8 -7 -6 -5 -4 -3 -2 -1
print(s[2:5])

Output:
llo
34. How Slicing Works In String Manipulation. Explain.

Syntax:
Str_Object[Start_Position:End_Position:Step]

s = 'HelloWorld'

Indexing:

H E L L O W O R L D

0 1 2 3 4 5 6 7 8 9
-10

-9 -8 -7 -6 -5 -4 -3 -2 -1
print(s[2:8:2])

Output:
loo
34. How Slicing Works In String Manipulation. Explain.

Syntax:
Str_Object[Start_Position:End_Position:Step]

s = 'HelloWorld'

Indexing:

H E L L O W O R L D

0 1 2 3 4 5 6 7 8 9
-10

-9 -8 -7 -6 -5 -4 -3 -2 -1
print(s[8:1:-1])

Output:
lroWoll
34. How Slicing Works In String Manipulation. Explain.

Syntax:
Str_Object[Start_Position:End_Position:Step]

s = 'HelloWorld'

Indexing:

H E L L O W O R L D

0 1 2 3 4 5 6 7 8 9
-10

-9 -8 -7 -6 -5 -4 -3 -2 -1
print(s[-4:-2])

Output:
or
34. How Slicing Works In String Manipulation. Explain.

Syntax:
Str_Object[Start_Position:End_Position:Step]

s = 'HelloWorld'

Indexing:

H E L L O W O R L D

0 1 2 3 4 5 6 7 8 9
-10

-9 -8 -7 -6 -5 -4 -3 -2 -1
print(s[::-1])

Output:
dlroWolleh
34. How Slicing Works In String Manipulation. Explain.

Syntax:
Str_Object[Start_Position:End_Position:Step]

s = 'HelloWorld' print(s[:]) #HelloWorld


print(s[::]) #HelloWorld
Indexing:
print(s[:5]) #Hello
H E L L O W O R L D print(s[2:5]) #llo
print(s[2:8:2]) #loo
0 1 2 3 4 5 6 7 8 9 print(s[8:1:-1]) #lroWoll
-10
print(s[-4:-2]) #or
-9 -8 -7 -6 -5 -4 -3 -2 -1 print(s[::-1])
#dlroWolleH
35. Can You Concatenate Two Tuples. If Yes, How Is It
Possible? Since it is Immutable?

How To Concatenate Two


Tuple:

t1 = (1,2,3)
t2 = (7,9,10)
t1 = t1 + t2
print("After concatenation is : ", t1 )

Output:
After concatenation is : (1, 2, 3, 7,
9, 10)
35. Can You Concatenate Two Tuples. If Yes, How Is It
Possible? Since it is Immutable?

Why Tuple Is Immutable and List Is


Mutable?
tuple_1 = (1,2,3) list_1 = [1,2,3]
print(id(tuple_1)) #140180965800128 print(id(list_1)) #140180965602048
tuple_2 = (7,9,10) list_2 = [7,9,10]
print(id(tuple_2)) #140180965665600 print(id(list_2)) #140180965601408
tuple_1 = tuple_1 + tuple_2 list_1.extend(list_2)
tuple_3 = tuple_1 list_3 = list_1
print("The tuple after concatenation is : ", tuple_1 ) print("The List after concatenation is : ", list_1 )
# The tuple after concatenation is : (1, 2, 3, 7, 9, # The List after concatenation is : [1, 2, 3, 7, 9, 10]
10) print(id(list_3)) #140180965602048
print(id(tuple_3)) #140180966177280

Tuple Ids: List Ids:


tuple_1 : list_1 :
#140180965800128 #140180965602048
tuple_2 : list_2 :
#140180965665600 #140180965601408
tuple_3 : list_3 :
#140180966177280 #140180965602048
36. Difference Between Python Arrays and Lists

LIST ARRAY

The list can store the value of different types. It can only consist of value of same type.

The list cannot handle the direct arithmetic operations. It can directly handle arithmetic operations.

The lists are the build-in data structure so we don't need to We need to import the array before work with the array
import it.

The lists are less compatible than the array to store the data. An array are much compatible than the list.

It consumes a large memory. It is a more compact in memory size comparatively list.

It is suitable for storing the longer sequence of the data item. It is suitable for storing shorter sequence of data items.

We can print the entire list using explicit looping. We can print the entire list without using explicit looping.

Source: https://www.javatpoint.com/python-array-vs-list
37. What Is _a, __a, __a__ in Python?

_a
❏ Python doesn't have real private methods, so one underline in the beginning of a variable/function/method name means
it's a private variable/function/method and It is for internal use only
❏ We also call it weak Private

__a
❏ Leading double underscore tell python interpreter to rewrite name in order to avoid conflict in subclass.
❏ Interpreter changes variable name with class extension and that feature known as the Mangling.
❏ In Mangling python interpreter modify variable name with __.
❏ So Multiple time It use as the Private member because another class can not access that variable directly.
❏ Main purpose for __ is to use variable/method in class only If you want to use it outside of the class you can make public
api.

__a__
❏ Name with start with __ and ends with same considers special methods in Python.
❏ Python provide this methods to use it as the operator overloading depending on the user.
❏ Python provides this convention to differentiate between the user defined function with the module’s function
38. How To Read Multiple Values From Single Input?

By Using Split()

x = list(map(int, input("Enter a multiple value: ").split()))


print("List of Values: ", x)

x = [int(x) for x in input("Enter multiple value: ").split()]


print("Number of list is: ", x)

x = [int(x) for x in input("Enter multiple value: ").split(",")]


print("Number of list is: ", x)
39. How To Copy and Delete A Dictionary

Delete By Using Copy A Dictionary Using Benefit Of Using Copy():


clear(): copy(): d2 = {'A':1,'B':2,'C':3}
d1 = {'A':1,'B':2,'C':3} d2 = {'A':1,'B':2,'C':3} print(d2) # {'A': 1, 'B': 2, 'C': 3}
d1.clear() print(d2) # {'A': 1, 'B': 2, 'C': 3} d3 = d2.copy()
print(d1) #{} d3 = d2.copy() print(d3) # {'A': 1, 'B': 2, 'C': 3}
print(d3) # {'A': 1, 'B': 2, 'C': 3} del d2['B']
print(d2) # {'A': 1, 'C': 3}
Delete By Using print(d3) # {'A': 1, 'B':2, 'C': 3}
pop(): Copy A Dictionary Using ‘=’:
d1 = {'A':1,'B':2,'C':3} d2 = {'A':1,'B':2,'C':3} DrawBack Of Using ‘=’
print(d1) #{'A': 1, 'B': 2, 'C': print(d2) # {'A': 1, 'B': 2, 'C': 3}
d2 = {'A':1,'B':2,'C':3}
3} d3 = d2
print(d2) # {'A': 1, 'B': 2, 'C': 3}
d1.pop('A') print(d3) # {'A': 1, 'B': 2, 'C': 3}
d3 = d2
print(d1) # {'B': 2, 'C': 3} print(d3) # {'A': 1, 'B': 2, 'C': 3}
del d2['B']
Delete By Using print(d2) # {'A': 1, 'C': 3}
del(): print(d3) # {'A': 1, 'C': 3}
del d1['B']
print(d1) # {'C': 3}
40. Difference Between Anonymous and Lambda Function

Lambda function:
❏ It can have any number of arguments but only one expression.
❏ The expression is evaluated and returned.
❏ Lambda functions can be used wherever function objects are required.

Anonymous function:
❏ In Python, Anonymous function is a function that is defined without a name.
❏ While normal functions are defined using the def keyword, Anonymous functions are defined using the
lambda keyword.
❏ Hence, anonymous functions are also called lambda functions.
40. Difference Between Anonymous and Lambda Function

Syntax:

lambda [arguments] : expression

Example:

square = lambda x : x * x
square(5) #25

The above lambda function definition is the same as the following function:
def square(x):
return x * x

Anonymous Function: We can declare a lambda function and call it as an anonymous function, without assigning it to a
variable.
print((lambda x: x*x)(5))

Above, lambda x: x*x defines an anonymous function and call it once by passing arguments in the parenthesis (lambda x: x*x)(5).
Advance Questions / Rarely asked

41. How to achieve Multiprocessing and Multithreading in


Python?

Multithreading:
❏ It is a technique where multiple threads are spawned by a process to do different tasks, at about the
same time, just one after the other.
❏ This gives you the illusion that the threads are running in parallel, but they are actually run in a
concurrent manner.
❏ In Python, the Global Interpreter Lock (GIL) prevents the threads from running simultaneously.

Multiprocessing:
❏ It is a technique where parallelism in its truest form is achieved.
❏ Multiple processes are run across multiple CPU cores, which do not share the resources among them.
❏ Each process can have many threads running in its own memory space.
❏ In Python, each process has its own instance of Python interpreter doing the job of executing the
instructions.

https://www.geeksforgeeks.org/difference-between-multithreading-vs-multiprocessing-in-
python/
https://www.geeksforgeeks.org/multiprocessing-python-set-1/
Advance Questions / Rarely asked

41. How to achieve Multiprocessing and Multithreading in Python?

# importing the multiprocessing module # A multithreaded program in


import multiprocessing python
import time
def print_cube(num):
from threading import Thread
print("Cube: {}".format(num * num * num))
num= 0
def print_square(num):
# The bottleneck of the code which is CPU-bound
print("Square: {}".format(num * num))
def upgrade(n):
while num<400000000:
if __name__ == "__main__":
num=num+1
# creating processes
p1 = multiprocessing.Process(target=print_square, args=(10,
# Creation of multiple threads
))
t1 = Thread(target=upgrade, args=(num//2,))
p2 = multiprocessing.Process(target=print_cube,
t2 = Thread(target=upgrade, args=(num//2,))
args=(10, ))
p1.start()
# multi thread architecture, recording time
p2.start()
start = time.time()
# wait until process 1 is finished
t1.start()
p1.join()
t2.start()
p2.join()
t1.join()
t2.join()
# both processes finished
end = time.time()
print("Done!")
print('Time taken in seconds -', end - start)
42. What is GIL. Explain

❏ The Global Interpreter Lock (GIL) of Python allows only one thread to be executed at a time. It is often a hurdle, as it does
not allow multi-threading in python to save time

❏ The Python Global Interpreter Lock or GIL, in simple words, is a mutex (or a lock) that allows only one thread to hold the
control of the Python interpreter.

❏ This means that only one thread can be in a state of execution at any point in time. The impact of the GIL isn’t visible to
developers who execute single-threaded programs, but it can be a performance bottleneck in CPU-bound and multi-
threaded code.

❏ Since the GIL allows only one thread to execute at a time even in a multi-threaded architecture with more than one CPU
core, the GIL has gained a reputation as an “infamous” feature of Python.

❏ Basically, GIL in Python doesn’t allow multi-threading which can sometimes be considered as a disadvantage.
43. How Class and Object Created in Python?

❏ Python is an object oriented programming language.


❏ Almost everything in Python is an object, with its properties and methods.
❏ A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class:
To create a class, use the keyword ‘class’:
class MyClass:
x=5

Create Object:
Now we can use the class named MyClass to create objects:
(Create an object named obj, and print the value of x:)

obj= MyClass()
print(obj.x)
44. Explain Namespace and Its Types in Python.

Namespace:
❏ In python we deal with variables, functions, libraries and modules etc.
❏ There is a chance the name of the variable you are going to use is already existing as name of
another variable or as the name of another function or another method.
❏ In such scenario, we need to learn about how all these names are managed by a python program.
This is the concept of namespace.
44. Explain Namespace and Its Types in Python.

Categories Of Namespace: Following are the three categories of namespace


❏ Local Namespace: All the names of the functions and variables declared by a program are held in this
namespace. This namespace exists as long as the program runs.

❏ Global Namespace: This namespace holds all the names of functions and other variables that are
included in the modules being used in the python program. It includes all the names that are part of the
Local namespace.

❏ Built-in Namespace: This is the highest level of namespace which is available with default names
available as part of the python interpreter that is loaded as the programing environment. It include Global
Namespace which in turn include the local namespace.

We can access all the names defined in the built-in namespace as follows.
builtin_names = dir(__builtins__)
for name in builtin_names:
print(name)
45. Explain Recursion by Reversing a List.

def reverseList(lst):
if not lst:
return []
return [lst[-1]] + reverseList(lst[:-1])

print(reverseList([1, 2, 3, 4, 5]))

Output:
[5,4,3,2,1]
46. What are Unittests in Python
Unit Testing is the first level of software testing where the smallest testable parts of a software are tested. This is used to
validate that each unit of the software performs as designed. The unittest test framework is python's xUnit style framework.
This is how you can import it.

import unittest

- Unit testing is a software testing method by which individual units of source code are put under various tests to
determine whether they are fit for use (Source). It determines and ascertains the quality of your code.
- Generally, when the development process is complete, the developer codes criteria, or the results that are known to be
potentially practical and useful, into the test script to verify a particular unit's correctness. During test case execution,
various frameworks log tests that fail any criterion and report them in a summary.
- The developers are expected to write automated test scripts, which ensures that each and every section or a unit meets
its design and behaves as expected.
- Though writing manual tests for your code is definitely a tedious and time-consuming task, Python's built-in unit testing
framework has made life a lot easier.
- The unit test framework in Python is called unittest, which comes packaged with Python.
- Unit testing makes your code future proof since you anticipate the cases where your code could potentially fail or
produce a bug. Though you cannot predict all of the cases, you still address most of them.
47. How to use Map, Filter and Reduce Function in Python?

Map() Function Filter() Function Reduce() Function


The map() function iterates through The filter() function takes a function The reduce() Function works differently than
all items in the given iterable and object and an iterable and creates a map() and filter(). It does not return a new
executes the function we passed as new list. list based on the function and iterable we've
an argument on each of them. As the name suggests, filter() forms a passed. Instead, it returns a single value.
new list that contains only elements
The syntax is: that satisfy a certain condition, i.e. the Also, in Python 3 reduce() isn't a built-in
map(function, iterable(s)) function we passed returns True. function anymore, and it can be found in the
functools module.
fruit = ["Apple", "Banana", "Pear"] The syntax is:
map_object = map(lambda s: s[0] filter(function, iterable(s)) The syntax is:
== "A", fruit) reduce(function, sequence[, initial])
print(list(map_object)) fruit = ["Apple", "Banana", "Pear"]
filter_object = filter(lambda s: s[0] == from functools import reduce
Output: "A", fruit) list = [2, 4, 7, 3]
[True, False, False] print(list(filter_object)) print(reduce(lambda x, y: x + y, list))
print("With an initial value: " +
Output: str(reduce(lambda x, y: x + y, list, 10)))
['Apple', 'Apricot']
Output:
16
With an initial value: 26
48. Difference Between Shallow Copy and Deep Copy

Shallow Copy:
Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the
elements. With a shallow copy, two collections now share the individual elements.

Shallow copying is creating a new object and then copying the non static fields of the current object to the new object. If the
field is a value type, a bit by bit copy of the field is performed. If the field is a reference type, the reference is copied but the
referred object is not, therefore the original object and its clone refer to the same object.

Deep Copy:
Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original
collection duplicated.

Deep copy is creating a new object and then copying the non-static fields of the current object to the new object. If a field is a
value type, a bit by bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is
performed. A deep copy of an object is a new object with entirely new instance variables, it does not share objects with the
old. While performing Deep Copy the classes to be cloned must be flagged as [Serializable].
49. How An Object Be Copied in Python

You can Explain Deep Copy and Shallow Copy


In This
50. What does term MONKEY PATCHING refer to in python?

In Python, the term monkey patch refers to dynamic (or run-time) modifications of a class or module. In Python,
we can actually change the behavior of code at run-time.

# monkey.py
class A:
def func(self):
print ("func() is called")

We use above module (monkey) in below code and change behavior of func() at run-time by assigning different value.

import monkey
def monkey_func(self):
print ("monkey_func() is called")

# replacing address of "func" with "monkey_func"


monkey.A.func = monkey_func
obj = monkey.A()

# calling function "func" whose address got replaced


# with function "monkey_func()"
obj.func()

Examples:
Output :monkey_func() is called
51. What is Operator Overloading & Dunder Method.

❏ Dunder methods in Python are special methods. Some Examples:


❏ In Python, we sometimes see method names with a double + __add__(self, other)
underscore (__), such as the __init__ method that every class – __sub__(self, other)
has. These methods are called “dunder” methods. * __mul__(self, other)
❏ In Python, Dunder methods are used for operator / __truediv__(self,
overloading and customizing some other function’s other)
// __floordiv__(self,
behavior.
other)
% __mod__(self, other)
** __pow__(self, other)
>> __rshift__(self, other)
<< __lshift__(self, other)
& __and__(self, other)
| __or__(self, other)
^ __xor__(self, other)
52. Draw Pattern.

# This is the example of print simple pyramid pattern


* *
* ****
n = int(input("Enter the number of rows")) * * **
* ***
# outer loop to handle number of rows * ** ***
for i in range(0, n):
* ** ****
* ***
# inner loop to handle number of columns * * ***
* **
# values is changing according to outer loop * **
for j in range(0, i + 1):
* * *
# printing stars *
print("* ", end="")
* 1
# ending line after each row
** 2 2
print()
*** 3 33
**** 4 444
Output: *****
5 5555
*
* *
* **
* ***
* ****
Thanks! Hope It Helps You!

Watch The Answers For The Remaining Questions On My Youtube


Channel.
Link For The Remaining Questions :

https://youtu.be/YeupGcOW-3k
Connect with me:
Youtube: https://www.youtube.com/c/nitmantalks
Instagram: https://www.instagram.com/nitinmangotra/
LinkedIn:
https://www.linkedin.com/in/nitin-mangotra-9a075a149
/
Facebook: https://www.facebook.com/NitManTalks/
Twitter: https://twitter.com/nitinmangotra07/
Telegram: https://t.me/nitmantalks/
Do Connect With Me!!!!

Please Do Comment Your Feedback In Comment Section Of My Video On


Youtube.
Here Is The Link: https://youtu.be/YeupGcOW-3k
When You Get Placed In Any Company Because Of My Video, DO Let Me Know.
It will Give Me More Satisfaction and Will Motivate me to make more such video
Content!!

Thanks
PS: Don’t Forget To Connect WIth ME.
Regards, Connect with me:
Youtube: https://www.youtube.com/c/nitmantalks
Nitin Mangotra (NitMan) Instagram:
https://www.instagram.com/nitinmangotra/
LinkedIn:
https://www.linkedin.com/in/nitin-mangotra-9a075a1
49/
Facebook: https://www.facebook.com/NitManTalks/
Twitter: https://twitter.com/nitinmangotra07/
Telegram: https://t.me/nitmantalks/

You might also like