Python is a general-purpose, dynamic, high-level, and interpreted programming language. It supports Object Oriented programming approach to develop applications. It is simple and easy to learn and provides lots of high-level data structures.

Python is an easy-to-learn yet powerful and versatile scripting language, which makes it attractive for Application Development.

With its interpreted nature, Python’s syntax and dynamic typing make it an ideal language for scripting and rapid application development.

Python supports multiple programming patterns, including object-oriented, imperative, and functional or procedural programming styles.

Python is not intended to work in a particular area, such as web programming. It is a multipurpose programming language because it can be used with web, enterprise, 3D CAD, etc.

We don’t need to use data types to declare variable because it is dynamically typed, so we can write a=10 to assign an integer value in an integer variable.

Intermediate Python interview questions aim to evaluate a candidate’s proficiency beyond the basics. These questions assess the candidate’s ability to work with more advanced Python features and solve problems that require a deeper understanding of the language’s capabilities. Topics may include object-oriented programming, data manipulation, error handling, and more.

Intermediate Python Interview Questions

For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and x range returns an xrange object.

This means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. That means that if you have a really gigantic range you’d like to generate a list for, say one billion, xrange is the function to use.

 

Comments in Python start with a # character. However, alternatively at times, commenting is done using docstrings(strings enclosed within triple quotes).

Example:

1
2
3 <span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_end"></span>
<pre><span>#Comments in Python start like this
print("Comments in Python start with a #")

Output:  Comments in Python start with a #

Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

 

Functions that return an iterable set of items are called generators.

 

In Python, the capitalize() method capitalizes the first letter of a string. If the string already consists of a capital letter at the beginning, then, it returns the original string.

To convert a string to lowercase, lower() function can be used.

Example:

1
2 stg='ABCD'
print(stg.lower())

Output: abcd

Multi-line comments appear in more than one line. All the lines to be commented are to be prefixed by a #. You can also a very good shortcut method to comment multiple lines. All you need to do is hold the ctrl key and left click in every place wherever you want to include a # character and type a # just once. This will comment all the lines where you introduced your cursor.

Docstrings are not actually comments, but, they are documentation strings. These docstrings are within triple quotes. They are not assigned to any variable and therefore, at times, serve the purpose of comments as well.

1
2
3
4
5
6
7
8 """
Using docstring as a comment.
This code divides 2 numbers
"""
x=8
y=4
z=x/y
print(z)

Output: 2.0

 

Operators are special functions. They take one or more values and produce a corresponding result.

is: returns true when 2 operands are true  (Example: “a” is ‘a’)

not: returns the inverse of the boolean value

in: checks if some element is present in some sequence

Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions. 

  1. Help() function: The help() function is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc.
  2. Dir() function: The dir() function is used to display the defined symbols.

Ans:

  1. Whenever Python exits, especially those Python modules which are having circular references to other objects or the objects that are referenced from the global namespaces are not always de-allocated or freed.
  2. It is impossible to de-allocate those portions of memory that are reserved by the C library.
  3. On exit, because of having its own efficient clean up mechanism, Python would try to de-allocate/destroy every other object.

The built-in datatypes in Python is called dictionary. It defines one-to-one relationship between keys and values. Dictionaries contain pair of keys and their corresponding values. Dictionaries are indexed by keys.

Let’s take an example:

The following example contains some keys. Country, Capital & PM. Their corresponding values are India, Delhi and Modi respectively.

1	dict={'Country':'India','Capital':'Delhi','PM':'Modi'}
1 print dict[Country]

Output:India

1	print dict[Capital]

Output:Delhi

1	print dict[PM]

Output:Modi

 

The Ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it.

Syntax:

The Ternary operator will be given as:
[on_true] if [expression] else [on_false]x, y = 25, 50big = x if x < y else y

Example:

The expression gets evaluated like if x<y else y, in this case if x<y is true then the value is returned as big=x and if it is incorrect then big=y will be sent as a result.

 

 

  1. What does this mean: *args, **kwargs ? And why would we use it ?

We use *args when we aren’t sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we don’t know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are a convention, you could also use *bob and **billy but that would not be wise.

 

We use *args when we aren’t sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we don’t know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are a convention, you could also use *bob and **billy but that would not be wise

To modify the strings, Python’s “re” module is providing 3 methods. They are:

  • split() – uses a regex pattern to “split” a given string into a list.
  • sub() – finds all substrings where the regex pattern matches and then replace them with a different string
  • subn() – it is similar to sub() and also returns the new string along with the no. of replacements.

The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ that is uses as first index and ‘1’ as the second index and the process goes on like that.

The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number.

The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order.

Python packages are namespaces containing multiple modules.

To delete a file in Python, you need to import the OS Module. After that, you need to use the os.remove() function.

Example:

1
2 import os
os.remove("xyz.txt")

 

Built-in types in Python are as follows –

  • Integers
  • Floating-point
  • Complex numbers
  • Strings
  • Boolean
  • Built-in functions

 

 

 

 

  1. Python’s lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python’s list comprehensions make them easy to construct and manipulate.
  2. They have certain limitations: they don’t support “vectorized” operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element.
  3. NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented.
  4. NumPy array is faster and You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc. 

 

Elements can be added to an array using the append()extend() and the insert (i,x) functions.

Example:

1
2
3
4
5
6
7 a=arr.array('d', [1.1 , 2.1 ,3.1] )
a.append(3.4)
print(a)
a.extend([4.5,6.3,6.8])
print(a)
a.insert(2,3.8)
print(a)

Output:

array(‘d’, [1.1, 2.1, 3.1, 3.4])

array(‘d’, [1.1, 2.1, 3.1, 3.4, 4.5, 6.3, 6.8])

array(‘d’, [1.1, 2.1, 3.8, 3.1, 3.4, 4.5, 6.3, 6.8])

Array elements can be removed using pop() or remove() method. The difference between these two functions is that the former returns the deleted value whereas the latter does not.

Example:

1
2
3
4
5 a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6])
print(a.pop())
print(a.pop(3))
a.remove(1.1)
print(a)

Output:

3.1

array(‘d’, [2.2, 3.8, 3.7, 1.2])

 

Python is an object-oriented programming language. This means that any program can be solved in python by creating an object model. However, Python can be treated as a procedural as well as structural language.

Check out these AI and ML courses by E & ICT Academy NIT Warangal to learn Python usage in AI ML and build a successful career.

Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.

Deep copy is used to store the values that are already copied. Deep copy doesn’t copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.

  1. Python has a multi-threading package but if you want to multi-thread to speed your code up, then it’s usually not a good idea to use it.
  2. Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your ‘threads’ can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread.
  3. This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core.
  4. All this GIL passing adds overhead to execution. This means that if you want to make your code run faster then using the threading package often isn’t a good idea.

The compiling and linking allow the new extensions to be compiled properly without any error and the linking can be done only when it passes the compiled procedure. If the dynamic loading is used then it depends on the style that is being provided with the system. The python interpreter can be used to provide the dynamic loading of the configuration setup files and will rebuild the interpreter.

The steps that are required in this as:

  1. Create a file with any name and in any language that is supported by the compiler of your system. For example file.c or file.cpp
  2. Place this file in the Modules/ directory of the distribution which is getting used.
  3. Add a line in the file Setup.local that is present in the Modules/ directory.
  4. Run the file using spam file.o
  5. After a successful run of this rebuild the interpreter by using the make command on the top-level directory.
  6. If the file is changed then run rebuildMakefile by using the command as ‘make Makefile’.

Python libraries are a collection of Python packages. Some of the majorly used python libraries are – NumpyPandasMatplotlibScikit-learn and many more.

The split() method is used to separate a given String in Python.

Example:

1
2 a="Kaashiv python"
print(a.split())

Output:  [‘Kaashiv’, ‘python’]

Modules can be imported using the import keyword.  You can import modules in three ways-

Example:

1
2
3 import array #importing using the original module name
import array as arr # importing using an alias name
from array import * #imports everything present in the array module

 

Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.

They are different types of inheritance supported by Python:

  1. Single Inheritance – where a derived class acquires the members of a single super class.
  2. Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 are inherited from base2.
  3. Hierarchical inheritance – from one base class you can inherit any number of child classes
  4. Multiple inheritance – a derived class is inherited from more than one base class.

Class in Python is created using the class keyword.

Example:

1
2
3
4
5 class Employee:
def __init__(self, name):
self.name = name
E1=Employee("abc")
print(E1.name)

Output: abc

 

In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time.

Consider the below example:

1
2
3
4 # m.py
class MyClass:
def f(self):
print "f()"

We can then run the monkey-patch testing like this:

1
2
3
4
5
6
7 import m
def monkey_f(self):
print "monkey_f()"

m.MyClass.f = monkey_f
obj = m.MyClass()
obj.f()

The output will be as below:

monkey_f()

As we can see, we did make some changes in the behavior of f() in MyClass using the function we defined, monkey_f(), outside of the module m.

Multiple inheritance means that a class can be derived from more than one parent classes. Python does support multiple inheritance, unlike Java.

It is used to determine the length of a string, a list, an array, etc.

Example:

1
2 stg='ABCD'
len(stg)

Output:4

Categorized in: