Last updated on Nov 21, 2023
Python is a high-level, interpreted, general-purpose programming language. Python can build any type of applications with its available tools/libraries. Python helps in modelling real-world problems and builds the applications to solve these issues. It supports objects, modules, threads, exception-handling and automatic memory management.
In this article, you can go through the set of python interview questions most frequently asked in the interview panel. This will help you crack the interview as the topmost industry experts curate these at HKR trainings.
Let us have a quick review of the python interview questions.
Ans:
Local Variables: The variables which are declared inside a function is known as a local variable. The scope of a variable is present in local space but not in global space.
Global Variables: The variables which are declared outside a function or in a global space are known as global variables. The scope of these variables is accessible by any function in the program.
Ans: Indentation is mandatory in python. The indentation specifies the block of code.The loops, classes,functions etc are specified with indentation to represent it as a code of an indented block. The indentation is provided with four space characters.If the code is not indented it may not execute accurately and throws an error.
Wish to make a career in the world of Python? Start with Python Training !
Ans: Unlike other programming codes, assignment “=” operator in python is not used in copying the objects; instead it creates a binding between the existing object and the target variable name. There are two ways of creating copies for the given object using the copy module.
Example:
from copy import copy, deepcopy
list_1 = [1, 2, [3, 5], 4]
## shallow copy
list_2 = copy(list_1)
list_2[3] = 9
list_2[2].append(7)
list_2 # output => [1, 2, [3, 5, 7], 9]
list_1 # output => [1, 2, [3, 5, 7], 4]
## deep copy
list_3 = deepcopy(list_1)
list_3[3] = 11
list_3[2].append(9)
list_3 # output => [1, 2, [3, 5, 7, 9], 11]
list_1 # output => [1, 2, [3, 5, 7], 4]
Ans: The “__init__” is a constructor method in python which automatically allocates memory when a new object/instance is created. All the classes in python have “__init__ “method associated with them. It distinguishes the methods and attributes of a class in local variables.
Example:
# class definition
class Student:
def __init__(self, fname, lname, age, section):
self.firstname = fname
self.lastname = lname
self.age = age
self.section = section
# creating a new object
stu1 = Student("James", "Nicholas", 18, "A1")
Ans:
Arrays:
Lists:
Ans:
Lists:
Syntax: list_1 = [3, ‘Thomas’, 7]
Tuples:
Syntax: tup_1 = (3, Thomas, 7)
Ans: Python classes are created using the keyword “class”.
Example:
class Candidate:
def __init__(self, name):
self.name = name
C1=Candidate("xyz")
print(C1.name)
Output: xyz
Ans: Inheritance allows a class to acquire the properties of another class. Inheritance provides the code reusability which makes easier to create and maintain an application. The class from which it is inheriting the properties is called a super class/base/parent class and the class that is inherited is called derived/child class. The different types of inheritance in python are.
IMAGE
Ans: Lambda in python is an anonymous function that accepts any number of arguments but can have a single expression. It is used in situations which requires the anonymous function for short during of time and is used in two ways.
Example:
mul = lambda a, b : a * b
print(mul(3, 7)) # output => 21
2.Wrapping lambda functions inside another function.
Example:
def myWrapper(n):
return lambda a : a * n
mulFive = myWrapper(3)
print(mulFive(5)) # output => 125
Ans: The keyword “pass” represents a null operation in python. In general, it is used in filling the empty blocks of code which may execute during the run time but has yet to be written.
Example:
def myFunc():
# do nothing
pass
myFunc() # nothing happens
Ans:
Ans:
Example:
"""
Using docstring as a comment.
This code divides 2 numbers
"""
x=10
y=5
z=x/y
print(z)
Output: 2.0
Ans:
Pass by value: It means that the copy of an actual object is passed such that changing the copy of an object will not change the value of an original object.
Pass by reference: It means that the reference to an object is passed such that changing the new object will change the value of an original object.
In Python, arguments are passed only by reference.
Example:
def affixNumber(arr):
arr.append(5)
arr = [1, 2, 3, 4]
print(arr) #Output: => [1, 2, 3, 4]
affixNumber(arr)
print(arr) #Output: => [1, 2, 3, 4, 5]
Ans: The operators are the special functions which take one or more values for producing the corresponding results.
is: The “is” operator returns true when the two operands are true.
not: The “not” operator returns the inverse of a boolean value.
in: The “in” operator will check if some element is present in some sequence.
Ans: Dictionary is the built-in data types in Python. The dictionaries define the one-to-one relationship between keys and values. It contains the pair of keys with its corresponding values and is indexed by keys.
Example:
dict={'State':'Telangana','District':'Hyderabad','Locality':'Charminar'}
|
1
|
print dict[State]
|
Telangana
1
|
print dict[District]
|
Hyderabad
1
|
print dict[Locality]
|
Charminar
In this example, the dictionary contains the key elements as State, District, Locality and their corresponding values as Telangana, Hyderabad and Charminar respectively.
Ans: Python libraries are a collection of python packages. The most frequently used python libraries are.
Ans: The “re” module in python provides these three methods for modifying the strings.
Ans: Python NumPy is used instead of lists because of the following reasons.
Ans:
Ans: As 2D plotting, 3D graphics is beyond the scope of NumPy and SciPy but there are certain packages in python that integrate with NumPy. The Matplotlib library provides basic 3D plotting in “mplot3d” subpackage. The “MayaVi” provides a wide range of high-quality 3D visualization features which utilizes the power of VTK engine.
Ans: The process of compilation and linking allows the new extensions for proper compilation without any errors and linking is done as it passes the compiled procedure. The python interpreter is used for providing the dynamic loading to set up the configuration files and rebuild the interpreter. The steps of process include.
Ans:
Break: It terminates the loop after the condition is met and then the control will be transferred to the next statement.
Continue: It skips some part of a loop when the condition is met and then the control will be transferred to the beginning of the loop.
Pass: It is used when you need some block of code syntactically but must skip its execution. It is basically a null operation and nothing happens when executed.
Ans:
Pickling is a process of a python module which accepts a python object and converts it into a string representation and then dumps it into a file by using a dump function.
Unpickling is a process of retrieving the original python objects from the stored string representation.
Ans: The commenting of a line is generally prefixed by a “#” character. The multi-line comments must be specified by prefixing with “#” character for each line. To do this, hold the “ctrl” key and “left-click” with mouse button in every place where you need a “#” character in that line.
Ans: The elements are added to an array by using append(), extend() and insert(i,x) functions.
Example:
a=arr.array('d', [1.5 , 2.5 ,3.5] )
a.append(5.6)
print(a)
a.extend([2.3,4.1,6.5])
print(a)
a.insert(3,1.8)
print(a)
Output:
array(‘d’, [1.5, 2.5, 3.5, 5.6])
array(‘d’, [1.5, 2.5, 3.5, 5.6, 2.3, 4.1, 6.5])
array(‘d’, [1.5, 2.5, 3.5, 1.8, 5.6, 2.3, 4.1, 6.5])
Ans:
Ans: As the name suggests the slicing is to take the parts of a list or tuple.
Syntax: [start : stop : step]
start: It represents the starting index from where to slice a list or tuple.
stop: It represents the ending index where it should stop.
step: It represents the number of steps required to jump.
The default values for start is 0, step is 1 and stop is the number of items in it.
Slicing is applicable on strings, arrays, lists and tuples.
[ Related Article: slicing in python ]
Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[1 : : 2])
output : [2, 4, 6, 8, 10]
Ans:
*args:
Example:
def multiply(x, y, *argv):
mul = x * y
for num in argv:
mul *= num
return mul
print(multiply(1, 2, 3, 4, 5))
Output: 120
**kwargs:
Example:
def tellArguments(**kwargs):
for key, value in kwargs.items():
print(key + ": " + value)
tellArguments(arg1 = "argument 1", arg2 = "argument 2", arg3 = "argument 3")
Output:
arg1: argument 1
arg2: argument 2
arg3: argument 3
Ans:
Example:
arr = [1, 3, 5, 7, 9, 11]
To get the last element, use the below statement.
print(arr[-1])
Output: 11
To get the second last element then use the below statement.
print(arr[-2])
Output: 9
Ans:
Ans: Python is an interpreter, 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 system 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.
Ans: 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.
Ans:
Ans: Self is merely a conventional name for the first argument of a method. A method defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for some instance x of the class in which the definition occurs; the called method will think it is called as meth(x, a, b, c).
If you have any doubts on python , then get them clarified from python Industry experts on our Python Community !
Ans: Use the popen2 module.
For example:
Import popen2
From child, to child = popen2.popen2("command")
tochild.write ("inputn")
tochild.flush ()
Output = fromchild.readline ()
Ans: Yes,you can create built-in modules containing functions, variables,exceptions and even new types in C.
Ans : Yes,using the C compatibility features found in C++. Place extern "C" { ... } around the Python include files and put extern "C" before each function that is going to be called by the Python interpreter. Global or static C++ objects with constructors are probably not a good idea.
Ans: The highest-level function to do this is PyRun_SimpleString () which takes a single string argument to be executed in the context of the module __main__ and returns 0 for success and -1 when an exception occurred (including Syntax Error).
Ans: Depending on your requirements, there are many approaches. To do this manually, begin by reading the "Extending and Embedding" document.Realize that for the Python run-time system, there isn't a whole lot of difference between C and C++ -- so the strategy of building a new Python type around a C structure (pointer) type will also work for C++ objects.
Ans:
@setlocal enable extensions & python -x %~f0 %* & go to :EOF
Ans : When using GDB with dynamically loaded extensions, you can't set a breakpoint in your extension until your extension is loaded.
In your .gdbinit file (or interactively), add the command:
Br _PyImport_LoadDynamicModule
Then, when you run GDB:
$ Gdb /local/bin/python
Gdb) run myscript.py
Gdb) continue # repeat until your extension is loaded
Gdb) finish # so that your extension is loaded
Gdb) br myfunction.c:50
Gdb) continue
Ans:"Freeze" is a program that allows you to ship a Python program as a single stand-alone executable file. It is not a compiler;your programs don't run any faster, but they are more easily distributable, at least to platforms with the same OS and CPU.
Batch starts on 6th Dec 2023 |
|
||
Batch starts on 10th Dec 2023 |
|
||
Batch starts on 14th Dec 2023 |
|