Python Interview Questions and Answers
Freshers / Beginner level questions & answers
Ques 1. What is Python?
Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high-level dynamic data types, and classes.
Python combines remarkable power with very clear syntax. It has interfaces to many systems calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface.
Finally, Python is portable: it runs on many Unix variants, on the Mac, and on PCs under MS-DOS, Windows, Windows NT, and OS/2.
Ques 2. What are the benefits of Python?
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.
Ques 3. What are the key features of Python?
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: 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 Python provides support to develop graphical user interfaces
Ques 4. What type of language is Python? Programming or Scripting?
Python is suitable for scripting, but in general, it is considered a general-purpose programming language.
Ques 5. What are the applications of Python?
The applications of Python are as follows:
- GUI-based desktop applications
- Image processing applications
- Business and Enterprise applications
- Prototyping
- Web and web framework applications
Ques 6. Define modules in Python?
The module is defined as a file that includes a set of various functions and Python statements that we want to add to our application.
Ques 7. What is the difference between .py and .pyc files?
py files are Python source files. .pyc files are the compiled bytecode files that are generated by the Python compiler.
Ques 8. Define String in Python?
String 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.
Ex:
- print("Hello")
- print('Hello')
Ques 9. What do you understand by the term namespace in Python?
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 of an object in Python:
Scope refers to the availability and accessibility of an object in the coding region.
Ques 10. Define iterators in Python?
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.
Ques 11. How does a function return values?
Functions return values using the return statement.
Ex:
def func():
num = 10
return num
Ques 12. Define slicing in Python?
Slicing is a procedure used to select a particular range of items from sequence types such as Strings, lists, and so on.
a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(3, 5)
print(a[x])
Output:
('d', 'e')
Ques 13. Define package in Python.
In Python packages are defined as the collection of different modules.
Ques 14. Which command is used to delete files in Python?
OS.unlink(filename) or OS.remove(filename) are the commands used to delete files in Python Programming. Example:
import OS
OS.remove('hello.txt')
Ques 15. Explain the difference between local and global namespaces?
- Local namespaces are created within a function when that function is called.
- Global namespaces are created when the program starts.
Ques 16. What is a boolean in Python?
Boolean is one of the built-in data types in Python, it mainly contains two values, which are true and false.
Python bool() is the method used to convert a value to a boolean value.
Ques 17. What are the functions in Python?
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.
Ques 18. Define self in Python?
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.
In the case of the init method, self refers to the newer creation of the object. Whereas in the case of other methods self refers to the object whose method was called.
Ques 19. How do we convert the string to lowercase?
The lower() function is used to convert string to lowercase.
Example:
str = "WithoutBook"
print(str.lower())
Output:
withoutbook
Ques 20. What is Try Block in python?
A block that is preceded by the try keyword is known as a try block.
Syntax:
try {
// Statements that may cause exception
}
Ques 21. Why do we use the split method in Python?
split() method in Python is mainly used to separate a given string.
Example:
txt = "welcome to the withoutbook"
x = txt.split()
print(x)
Output:
['welcome', 'to', 'the', 'withoutbook']
Ques 22. Can we make multi-line comments in Python?
In python, there is no specific syntax to display multi-line comments like in other languages. In order to display multi-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 the Python parser.
Ques 23. What are the OOP's concepts available in Python?
Python is also an object-oriented programming language like other programming languages. It also contains different OOP's concepts, and they are
- Object
- Class
- Method
- Encapsulation
- Abstraction
- Inheritance
- Polymorphism
Ques 24. Define object in Python.
An object in Python is defined as an instance that has both state and behavior. Everything in Python is made of objects.
Ques 25. What is a class in Python?
Class is defined as a logical entity that is a huge collection of objects and it also contains both methods and attributes.
Ques 26. How to create a class in Python?
In Python programming, the class is created using a class keyword. The syntax for creating a class is as follows:
Example:
class ClassName:
code statement
Ques 27. What is the syntax for creating an instance of a class in Python?
The syntax for creating an instance of a class is as follows:
<object-name> = <class-name>(<arguments>)
Ques 28. Define what is “Method” in Python programming.
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 object can have methods.
Ques 29. Why can't I use an assignment in an expression?
Many people used to C or Perl complain that they want to use this C idiom: while (line = readline(f)) {
...do something with line...
}
where in Python you're forced to write this:
while True:
line = f.readline() if not line:
break
...do something with line...
The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages, caused by this construct:
if (x = 0) {
...error handling...
}
else {
...code that only works for nonzero x...
}
The error is a simple typo: x = 0, which assigns 0 to the variable x, was written while the comparison x == 0 is certainly what was intended.
Many alternatives have been proposed. Most are hacks that save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct.
Ques 30. How do you set a global variable in a function in Python?
x = 1 # make a global
def f():
print x # try to print the global
for j in range(100):
if q>3:
x=4
Any variable assigned in a function is local to that function. unless it is specifically declared global. Since a value is bound to x as the last statement of the function body, the compiler assumes that x is local. Consequently, the print x attempts to print an uninitialized local variable and will trigger a NameError.
The solution is to insert an explicit global declaration at the start of the function:
def f():
global x
print x # try to print the global
for j in range(100):
if q>3:
x=4
In this case, all references to x are interpreted as references to the x from the module namespace.
Ques 31. What are the rules for local and global variables in Python?
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function's body, it's assumed to be local.
If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as 'global'.
Though a bit surprising at first, a moment's consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you'd be using global all the time.
You'd have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.
Ques 32. How do I share global variables across modules?
The canonical way to share information across modules within a single program is to create a special module (often called config or cfg).
Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere.
For example:
config.py: x = 0 # Default value of the 'x' configuration setting
mod.py: import config
config.x = 1
main.py:import config
import mod
print config.x
Note that using a module is also the basis for implementing the Singleton design pattern, for the same reason.
Ques 33. How can I pass optional or keyword parameters from one function to another?
Collect the arguments using the * and ** specifier in the function's parameter list; this gives you the positional arguments as a tuple and the keyword arguments as a dictionary. You can then pass these arguments when calling another function by using * and **:
def f(x, *tup, **kwargs):
kwargs['width']='14.3c'
g(x, *tup, **kwargs)
In the unlikely case that you care about Python versions older than 2.0, use 'apply':
def f(x, *tup, **kwargs):
kwargs['width']='14.3c'
apply(g, (x,)+tup, kwargs)
Ques 34. How do you make a higher order function in Python?
You have two choices: you can use nested scopes or you can use callable objects.
For example,
suppose you wanted to define linear(a,b) which returns a function f(x) that computes the value a*x+b. Using nested scopes:
def linear(a,b):
def result(x):
return a*x + b
return result
Or using a callable object:
class linear:
def __init__(self, a, b):
self.a, self.b = a,b
def __call__(self, x):
return self.a * x + self.b
In both cases:
taxes = linear(0.3,2)
gives a callable object where taxes(10e6) == 0.3 * 10e6 + 2.
The callable object approach has the disadvantage that it is a bit slower and results in slightly longer code. However, note that a collection of callables can share their signature via inheritance:
class exponential(linear):
# __init__ inherited
def __call__(self, x):
return self.a * (x ** self.b)
Object can encapsulate state for several methods: class counter:
value = 0
def set(self, x): self.value = x
def up(self): self.value=self.value+1
def down(self): self.value=self.value-1
count = counter()
inc, dec, reset = count.up, count.down, count.set
Here inc(), dec() and reset() act like functions which share the same counting variable.
Ques 35. How do I copy an object in Python?
In general, try copy.copy() or copy.deepcopy() for the general case. Not all objects can be copied, but most can.
Some objects can be copied more easily. Dictionaries have a copy() method: newdict = olddict.copy()
Sequences can be copied by slicing: new_l = l[:]
Ques 36. How can I find the methods or attributes of an object?
For an instance x of a user-defined class, dir(x) returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class.
Ques 37. How do I convert a string to a number?
For integers, use the built-in int() type constructor, e.g. int('144') == 144. Similarly, float() converts to floating-point, e.g. float('144') == 144.0.
By default, these interpret the number as decimal, so that int('0144') == 144 and int('0x144') raises ValueError.
int(string, base) takes the base to convert from as a second optional argument, so int('0x144', 16) == 324. If the base is specified as 0, the number is interpreted using Python's rules: a leading '0' indicates octal, and '0x' indicates a hex number.
Do not use the built-in function eval() if all you need is to convert strings to numbers. eval() will be significantly slower and it presents a security risk: someone could pass you a Python expression that might have unwanted side effects. For example, someone could pass __import__('os').system("rm -rf $HOME") which would erase your home directory.
eval() also has the effect of interpreting numbers as Python expressions, so that e.g. eval('09') gives a syntax error because Python regards numbers starting with '0' as octal (base 8).
Ques 38. How can my code discover the name of an object?
Generally speaking, it can't, because objects don't really have names. Essentially, assignment always binds a name to a value; The same is true of def and class statements, but in that case the value is a callable. Consider the following code:
class A:
pass
B = A
a = B()
b = a
print b
<__main__.A instance at 016D07CC>
print a
<__main__.A instance at 016D07CC>
Arguably the class has a name: even though it is bound to two names and invoked through the name B the created instance is still reported as an instance of class A. However, it is impossible to say whether the instance's name is a or b, since both names are bound to the same value.
Generally speaking it should not be necessary for your code to "know the names" of particular values. Unless you are deliberately writing introspective programs, this is usually an indication that a change of approach might be beneficial.
In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to this question:
The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn't really care -- so the only way to find out what it's called is to ask all your neighbours (namespaces) if it's their cat (object)
....and don't be surprised if you'll find that it's known by many names, or no name at all!
Ques 39. Is there an equivalent of C's "?:" ternary operator?
No.
Ques 40. How do I convert a number to a string in Python?
- To convert, e.g., the number 144 to the string '144', use the built-in function str().
- If you want a hexadecimal or octal representation, use the built-in functions hex() or oct().
- For fancy formatting, use the % operator on strings, e.g. "%04d" % 144 yields '0144' and "%.3f" % (1/3.0) yields '0.333'.
Ques 41. How do I modify a string in place?
You can't, because strings are immutable. If you need an object with this ability, try converting the string to a list or use the array module:
>>> s = "Hello, world" >>> a = list(s)
>>>print a
['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> a[7:] = list("there!")
>>>''.join(a)
'Hello, there!'
>>> import array
>>> a = array.array('c', s) >>> print a
array('c', 'Hello, world')
>>> a[0] = 'y' ; print a
array('c', 'yello world')
>>> a.tostring()
'yello, world'
Ques 42. How do I use strings to call functions/methods in Python?
There are various techniques.
* The best is to use a dictionary that maps strings to functions. The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct:
def a():
pass
def b():
pass
dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
dispatch[get_input()]() # Note trailing parens to call function
Use the built-in function getattr():
import foo
getattr(foo, 'bar')()
Note that getattr() works on any object, including classes, class instances, modules, and so on. This is used in several places in the standard library, like this:
class Foo:
def do_foo(self):
def do_bar(self):
f = getattr(foo_instance, 'do_' + opname)
f()
- Use locals() or eval() to resolve the function name:
def myFunc(): print "hello" fname = "myFunc" f = locals()[fname] f() f = eval(fname) f()
Note: Using eval() is slow and dangerous. If you don't have absolute control over the contents of the string, someone could pass a string that resulted in an arbitrary function being executed.
Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?
Starting with Python 2.2, you can use S.rstrip("\r\n") to remove all occurences of any line terminator.
from the end of the string S without removing other trailing whitespace. If the string S represents more
than one line, with several empty lines at the end, the line terminators for all the blank lines will be
removed:
>>> lines = ("line 1 "
...
... )
>>> lines.rstrip(" ")
"line 1"
Since this is typically only desired when reading text one line at a time, using S.rstrip() this way works
well.
For older versions of Python, There are two partial substitutes:
* If you want to remove all trailing whitespace, use the rstrip() method of string objects. This removes all trailing whitespace, not just a single newline.
* Otherwise, if there is only one line in the string S, use S.splitlines()[0].
Is there a scanf() or sscanf() equivalent?
Not as such.
For simple input parsing, the easiest approach is usually to split the line into whitespace-delimited words using the split() method of string objects and then convert decimal strings to numeric values using int() or float(). split() supports an optional "sep" parameter which is useful if the line uses something other than whitespace as a separator.
For more complicated input parsing, regular expressions more powerful than C's sscanf() and better suited for the task.
Ques 43. What is the difference between a list and a tuple in Python?
The difference between a tuple and list in python is as follows:
List | Tuple |
The list is mutable (can be changed) | A tuple is immutable (remains constant) |
These lists performance is slower | Tuple performance is faster when compared to lists |
Syntax: list_1 = [20, ‘Mindmajix’, 30] | Syntax: tup_1 = (20, ‘Mindmajix’, 30) |
Ques 44. Define PYTHON PATH?
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.
Ques 45. What are the two major loop statements?
Two major loop statements are:
- for
- while
Ques 46. What do you understand by the term PEP 8?
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.
Ques 47. What are the built-in types available in Python?
The built-in types in Python are as follows:
- Integer
- Complex numbers
- Floating-point numbers
- Strings
- Built-in functions
Ques 48. What are Python Decorators?
Decorator is the most useful tool in Python as it allows programmers to alter the changes in the behavior of class or function.
Ques 49. How do we find bugs and statistical problems in Python?
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.
Ques 50. How do you invoke the Python interpreter for interactive use?
By using python or pythonx.y we can invoke a Python interpreter. where x.y is the version of the Python interpreter.
Ques 51. How can Python be an interpreted language?
As in Python the code which we write is not machine-level code before runtime so, this is the reason why Python is called an interpreted language.
Ques 52. What happens when a function doesn’t have a return statement? Is this valid?
Yes, this is valid. The function will then return a None object. The end of a function is defined by the block of code that is executed (i.e., the indenting) not by any explicit keyword.
Ques 53. How can we make a Python script executable on Unix?
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 #.
Ques 54. What are Dict and List comprehensions in Python?
These are mostly used as syntax constructions to ease the creation of lists and dictionaries based on existing iterable.
Ques 55. Define the term lambda.
Lambda is the small anonymous function in Python that is often used as an inline function.
Ques 56. When would you use triple quotes as a delimiter?
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.
Ques 57. How do we reverse a list in Python?
By using the list.reverse(): we can reverse the objects of the list in Python.
Ques 58. Does multiple inheritances are supported in Python?
Multiple inheritances are supported in python. It is a process that provides flexibility to inherit multiple base classes in a child class.
Ques 59. Define Constructor in Python.
Constructor is a special type of method with a block of code to initialize the state of instance members of the class. A constructor is called only when the instance of the object is created. It is also used to verify that they are sufficient resources for objects to perform a specific task.
There are two types of constructors in Python, and they are:
- Parameterized constructor
- Non-parameterized constructor
Ques 60. What is the best Python IDE for beginners?
There are many IDE’s to execute Python code. But, as a beginner, the following two IDE’s will be helpful
- PyCharm
- Spyder
Ques 61. How do I prepare for a Python interview?
- First of all, learn how to write code in the white paper without any support (IDE)
- Maintain basic Python control flow
- Be confident in explaining your program flow
- Learn where to use oops concepts and generators
Ques 62. Why should you choose Python?
There is no doubt, Python is the best choice for coding in the interview. Other than Python, if you prefer to choose C++ or java you need to worry about structure and syntax.
Ques 63. Can we use Python for coding in interviews?
Choosing an appropriate language to code also matters at the time of the interview. Any language can be used for coding but coding in Python is seeming less and easy.
Intermediate / 1 to 5 years experienced level questions & answers
Ques 64. How memory management is done in Python?
- 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.
Ques 65. What are the differences between Java and Python?
Please refer Java vs Python.
Ques 66. Define pickling and unpickling in Python.
Pickling in Python: The process in which the pickle module accepts various Python objects and converts them into a string representation and dumps the file accordingly using the dump function is called pickling.
Unpickling in Python: The process of retrieving actual Python objects from the stored string representation is called unpickling.
Ques 67. What are Python String formats and Python String replacements?
Python String Format: The String format() method in Python is mainly used to format the given string into an accurate output or result.
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.
Ques 68. Name some of the built-in modules in Python.
The built-in modules in Python are:
- sys module
- OS module
- random module
- collection module
- JSON
- Math module
Ques 69. What is _init_?
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.
Ques 70. Define generators in Python?
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.
Ques 71. Define docstring in Python?
The docstring in Python is also called a documentation string, it provides a way to document the Python classes, functions, and modules.
Ques 72. How to remove values from a Python array?
The elements can be removed from a Python array using the remove() or pop() function. The difference between pop() and remove() will be explained in the below example.
Example of remove():
fruits = ['apple', 'banana', 'cherry']
fruits.remove('banana')
print(fruits)
Output:
['apple', 'cherry']
Example of pop():
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
print(fruits)
Output:
['apple', 'cherry']
Ques 73. How do Python arrays and lists differ from each other?
The difference between Python array and Python list is as follows:
Arrays | Lists |
The array is defined as a linear structure that is used to store only homogeneous data. | The list is used to store arbitrary and heterogeneous data |
Since array stores only a similar type of data so it occupies less amount of memory when compared to the list. | List stores different types of data so it requires a huge amount of memory |
The length of the array is fixed at the time of designing and no more elements can be added in the middle. | The length of the list is no fixed, and adding items in the middle is possible in lists. |
Ques 74. What is the difference between range and xrange?
Both methods are mainly used in Python to iterate the for loop for a fixed number of times. They differ only when we talk about Python versions.
The difference between range and xrange is as follows:
Range() method | Xrange() method |
The xrange() method is not supported in Python3 so that the range() method is used for iteration in for loops. | The xrange() method is used only in Python version 2 for the iteration in loops. |
The list is returned by this range() method | It only returns the generator object because it doesn’t produce a static list during run time. |
It occupies a huge amount of memory as it stores the complete list of iterating numbers in memory. | It occupies less memory because it only stores one number at a time in memory. |
Ques 75. What is data abstraction in Python?
In simple words, abstraction can be defined as hiding unnecessary data and showing or executing necessary data. In technical terms, abstraction can be defined as hiding internal processes and showing only the functionality. In Python abstraction can be achieved using encapsulation.
Ques 76. Define encapsulation in Python.
Encapsulation is one of the most important aspects of object-oriented programming. The 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.
Ques 77. What is polymorphism in Python?
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.
Ques 78. Does Python make use of access specifiers?
Python does not make use of access specifiers and also it does not 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 behavior of private and protected access specifiers.
Ques 79. How can we create an empty class in Python?
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 keywords and object to this class can be created outside the class itself.
Ques 80. How can we create a constructor in Python programming?
The _init_ method in Python stimulates the constructor of the class.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Output:
John
16
Ques 81. Define Inheritance in Python?
When an object of child class has the ability to acquire the properties of a parent class then it is called inheritance. It is mainly used to acquire runtime polymorphism and also it provides code reusability.
Ques 82. What are the cool things you can do with Python?
The following are some of the things that you can perform using Python:
- Automate tasks
- Play games
- Build a Blockchain to mine Bitcoins
- Build a chatbot interface combined with AI
Experienced / Expert level questions & answers
Ques 83. What are the differences between Python 2 and Python 3?
Please refer Python 2 vs Python 3.
Ques 84. How can we access a module written in Python from C?
We can access the module written in Python from C by using the following method.
Module == PyImport_ImportModule("<modulename>");
Ques 85. How do you copy an object in Python?
To copy objects in Python we can use methods called copy.copy() or copy.deepcopy().
Example:
fruits = ["apple", "banana", "cherry"]
x = fruits.copy()
print(x)
Output:
['apple', 'banana', 'cherry']
Ques 86. What is the procedure to install Python on Windows and set path variables?
We need to implement the following steps to install Python on Windows, and they are:
- First, you need to install Python from https://www.python.org/downloads/
- 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 a 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%.
Ques 87. Differentiate between SciPy and NumPy?
The difference between SciPy and NumPy is as follows:
NumPy | SciPy |
Numerical Python is called NumPy | Scientific Python is called SciPy |
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 | This is an entire collection of tools in Python mainly used to perform operations like differentiation, integration and many more. |
There are some of the linear algebraic functions present in this module but they are not fully fledged. | For performing algebraic computations this module contains some of the fully-fledged operations |
Ques 88. What is Django? What are different interview questions and answers on Django?
Please refer Django interview questions and answers.
Ques 89. List the ways we add view functions to urls.py.
- Adding a function view
- Adding a class-based view
Ques 90. What is flask and provide some interview questions and answers?
Please refer Flask interview questions and answers.
Ques 91. What is the Dogpile effect?
This is defined as an occurrence of an event when the cache expires and also when the websites are hit with more 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 begins generating new value.
Ques 92. Does Python replace Java?
Python alone can't replace Java, whereas a group of programming languages can replace Java but JVM can't be replaced.
Ques 93. How to crack a coding interview?
It is not that easy as we usually think. Mugging up some programs and executing the same will not work. The ideal way to crack the coding interview, you should be proficient in writing code without the support of any IDE. Don't panic or argue, test your code before you submit, wait for their feedback. Practicing mock interviews will help.
Ques 94. Top 5 tips to crack the python interview?
The following are the top 5 tips to crack Python interview:
- Building a proper profile will fetch you better results
- Setting up your portfolio might impress your interviewer
- Learn all the fundamentals of Python and OOps concepts as 90% of the interview start from basics
- Feel free to write code pen and paper
- Apart from all the above practice is what required.
Ques 95. What is nested function in Python?
In Python, we can create a function inside another function. This is known as a nested function. For example,
def greet(name):
# inner function
def display_name():
print("Hi", name)
# call inner function
display_name()
# call outer function
greet("John")
Output:
Hi John
In the above example, we have defined the display_name() function inside the greet() function.
Here, display_name() is a nested function. The nested function works similar to the normal function. It executes when display_name() is called inside the function greet().
Ques 96. What is Python Closures?
As we have already discussed, closure is a nested function that helps us access the outer function's variables even after the outer function is closed. For example,
def greet():
# variable defined outside the inner function
name = "John"
# return a nested anonymous function
return lambda: "Hi " + name
# call the outer function
message = greet()
# call the inner function
print(message())
Output:
Hi John
In the above example, we have created a function named greet() that returns a nested anonymous function.
Ques 97. When to use closures? So what are closures good for?
Closures can be used to avoid global values and provide data hiding, and can be an elegant solution for simple cases with one or few methods.
However, for larger cases with multiple attributes and methods, a class implementation may be more appropriate.
Ques 98. What is the difference between append() and extend() methods?
Both append() and extend() methods are methods used to add elements at the end of a list.
- append(element): Adds the given element at the end of the list that called this append() method
- extend(another-list): Adds the elements of another list at the end of the list that called this extend() method
Ques 99. How is Multithreading achieved in Python?
Python has a multi-threading package ,but commonly not considered as good practice to use it as it will result in increased code execution time.
- Python has a constructor called the Global Interpreter Lock (GIL). The GIL ensures that only one of your ‘threads’ can execute at one time.The process makes sure that a thread acquires the GIL, does a little work, then passes the GIL onto the next thread.
- This happens at a very Quick instance of time and that’s why to the human eye it seems like your threads are executing parallely, but in reality they are executing one by one by just taking turns using the same CPU core.
Ques 100. What is functional programming? Does Python follow a functional programming style? If yes, list a few methods to implement functionally oriented programming in Python.
Functional programming is a coding style where the main source of logic in a program comes from functions.
Incorporating functional programming in our codes means writing pure functions.
Pure functions are functions that cause little or no changes outside the scope of the function. These changes are referred to as side effects. To reduce side effects, pure functions are used, which makes the code easy-to-follow, test, or debug.
Python does follow a functional programming style.
Ques 101. What is monkey patching in Python?
Monkey patching is the term used to denote the modifications that are done to a class or a module during the runtime. This can only be done as Python supports changes in the behavior of the program while being executed.
Ques 102. What is pandas?
Pandas is an open source python library which supports data structures for data based operations associated with data analyzing and data Manipulation. Pandas with its rich sets of features fits in every role of data operation,whether it be related to implementing different algorithms or for solving complex business problems. Pandas helps to deal with a number of files in performing certain operations on the data stored by files.
Ques 103. What are dataframes?
A dataframe refers to a two dimensional mutable data structure or data aligned in the tabular form with labeled axes(rows and column).
- data:It refers to various forms like ndarray, series, map, lists, dict, constants and can take other DataFrame as Input.
- index:This argument is optional as the index for row labels will be automatically taken care of by pandas library.
- columns:This argument is optional as the index for column labels will be automatically taken care of by pandas library.
- Dtype: refers to the data type of each column.
Ques 104. What is regression?
Regression is termed as supervised machine learning algorithm technique which is used to find the correlation between variables and help to predict the dependent variable(y) based upon the independent variable (x). It is mainly used for prediction, time series modeling, forecasting, and determining the causal-effect relationship between variables.
Scikit library is used in python to implement the regression and all machine learning algorithms.
There are two different types of regression algorithms in machine learning :
Linear Regression: Used when the variables are continuous and numeric in nature.
Logistic Regression: Used when the variables are continuous and categorical in nature.
Ques 105. What is classification?
Classification refers to a predictive modeling process where a class label is predicted for a given example of input data. It helps categorize the provided input into a label that other observations with similar features have. For example, it can be used for classifying a mail whether it is spam or not, or for checking whether users will churn or not based on their behavior.
These are some of the classification algorithms used in Machine Learning:
- Decision tree
- Random forest classifier
- Support vector machine
Ques 106. What is SVM?
Support vector machine (SVM) is a supervised machine learning model that considers the classification algorithms for two-group classification problems. Support vector machine is a representation of the training data as points in space are separated into categories with the help of a clear gap that should be as wide as possible.
Most helpful rated by users:
- What is Python?
- How do I share global variables across modules?
- How do you set a global variable in a function in Python?
- Why can't I use an assignment in an expression?
- What are the rules for local and global variables in Python?
Related differences
Related interview subjects
Python interview questions and answers - Total 106 questions |
Python Pandas interview questions and answers - Total 48 questions |
Python Matplotlib interview questions and answers - Total 30 questions |
Django interview questions and answers - Total 50 questions |
Pandas interview questions and answers - Total 30 questions |
Deep Learning interview questions and answers - Total 29 questions |
Flask interview questions and answers - Total 40 questions |
PySpark interview questions and answers - Total 30 questions |
PyTorch interview questions and answers - Total 25 questions |
Data Science interview questions and answers - Total 23 questions |
SciPy interview questions and answers - Total 30 questions |
Generative AI interview questions and answers - Total 30 questions |
NumPy interview questions and answers - Total 30 questions |