Python Interview Questions
- By Abhishek Thakur
- 0 Comments
> Python can be used on a server to create web applications.
> Python can be used alongside software to create workflows.
> Python can connect to database systems. It can also read and modify files.
> Python is nowadays widely used in Machine Learning, Deep Learning, Artificial intelligence, and more
> Python can be used to handle big data and perform complex mathematics.
> Python can be used for rapid prototyping or production-ready software development.
> In the near future, Python will be able for making Android Apps too
> Stable and Transparent
> Print statement is treated as statement and not function.
> ASCII string type is used by default to store strings
> Range function reconstructs the sequence every time
> It returns an integer to the nearest whole number when dividing two integers
> It is the future of python
> The print syntax is treated as a function
> Unicode is the implicit string type by default
> The range is replaced by range() function
> It makes integer division more intuitive by using true division for integers and floats
> They are parameters/arguments supplied to the program when the program is invoked.
> They are used to control the program from outside instead of hard coding those values inside code.
To use sys.argv, you will have to import sys. The first argument, sys.argv, is the name of the program as it was invoked, and sys.argv is the first argument you pass to the program.
mytuple = (“a”, “b”, “c”)
myiterator = iter(mytuple)
> The generator function has a yield statement.
> When called, it returns an object that is an iterator but does not start execution immediately.
> Methods like iter() and next() are implemented automatically. So iteration through items using next() is possible.
> Finally, when the function ends, the StopIteration method is raised automatically on further calls.
lambda arguments: expression
Example: x = lambda g: g **2
for x in mydict:
def _ _init__(self, name, age):
self.name = name
self.age = age
print(“Hello my name is ” + self.name)
p1 = Person(“Selmon Bhai”, 90) p1.myfunc()
def _ _init__(self, fname, lname):
Encapsulation is an important pillar of object-oriented programming. It is used to restrict access to methods and variables. In encapsulation, code and data are wrapped together within a single unit and protected from being modified by accident.
Abstraction is used to hide internal details and show only functionalities. Abstracting something means to give names to things so that name captures the core of what a function or a whole program does.
Procedural programming uses a list of instructions to do computation step by step. In procedural programming, It is not easy to maintain the codes when the project becomes lengthy. It doesn’t simulate the real world. It works on step-by-step instructions divided into small parts called functions. Procedural language doesn’t provide any proper way for data binding, so it is fewer data from anywhere. secure.
> Thread Identifier: Unique id is assigned to every thread
> Stack pointer: Points to thread’s stack in the process.
> Program counter: a register that stores the address of the instruction currently being executed by the thread.
> Thread state: can be running, ready, waiting, start or do.
> Thread’s register set: registers assigned to thread for computations.
> Parent process Pointer: A pointer to the Process control block (PCB) of the process that the thread lives on.
> get() − It removes and returns an item from the queue.
> put() − The put adds the item to a queue.
> qsize() – It returns the number of items that are currently in the queue.
> empty() − It returns True if queue is empty; otherwise, False.
> full() − It returns True if queue is full; otherwise, False.
> The allocation of Python heap space for Python objects is done by the Python memory manager. The core API gives access to some tools for the programmer to code.
> Python also has an inbuilt garbage collector, which recycles all the unused memory and frees the memory, and makes it available to the heap space.
# -*- coding: encoding -*-
In the above line, we can replace encoding with the encoding that we want to use.
> Syntax: A Tuple is enclosed in parentheses:
E.g. myTuple = (10, 20, “vieh”, “group”);
A List is enclosed in brackets:
E.g. myList = [10, 20, 30];
> Mutable: Tuple is an immutable data structure. Whereas, a List is a mutable data structure.
> Size: A Tuple takes much lesser space than a List in Python.
> Performance: Tuple is faster than a List in Python. So it gives us a good performance.
> Use case: Since Tuple is immutable, we can use it in cases like Dictionary creation. Whereas, a List is preferred in the use case where data can alter.
> Syntax: In a List we store objects in a sequence. In a Dictionary we store objects in key-value pairs.
> Reference: In List we access objects by index number. It starts from 0 index. In a Dictionary we access objects by key specified at the time of Dictionary creation.
> Ordering: In a List objects are stored in an ordered sequence. In a Dictionary objects are not stored in an ordered sequence.
> Hashing: In a Dictionary, keys have to be hashable. In a List, there is no need for hashing.
E.g. the set of built-in exception names, the set of built-in names, local names in a function. At different moments in Python, different Namespaces are created. Each Namespace in Python can have a different lifetime. For the list of built-in names, Namespace is created when the Python interpreter starts. When the Python interpreter reads the definition of a module, it creates a global namespace for that module. When a Python interpreter calls a function, it creates a local namespace for that function.
Some of the use cases of pass statement is:
a) It can be used in Syntax Purposes:
>>> while True:
………pass # Wait till user input is received
b) It can be used for creating minimal classes:
>>> class VIEHGroup:
c) We can also use it as a placeholder for TODO work on a function or code that needs to be implemented at a later point of time.
>>> def initialization():
… pass # TODO
1) Shallow Copy: To create a shallow copy we call copy.copy(x). In a shallow copy, Python creates a new compound object based on the original object. And it tries to put references from the original object into copy object.
2) Deep Copy: To create a deep copy, we call copy.deepcopy(x). In a deep copy, Python creates a new object and recursively creates and inserts copies of the objects from original object into copy object. In a deep copy, we may face the issue of recursive loop due to infinite recursion.
10// 4 = 2
-10//4 = -3
We call append() method to add an item to the end of a list.
We call extend() method to add another list to the end of a list.
In append() we have to add items one by one. But in extend() multiple items from another list can be added at the same time.
E.g. ‘a b c ‘.split() returns [‘a’, ‘b’, ‘c’]
Slicing is a way of getting substring from a String. It returns another String.
E.g. >>> ‘a b c'[2:3] returns b
>>>print name[:5] + name[5:]
The output of this will be VIEH Group
This is an example of Slicing. Since we are slicing at the same index, the first name[:5] gives the substring name up to the 5th location excluding the 5th location. The name[5:] gives the rest of the substring of the name from the 5th location. So we get the full name as output.
Local Variables:Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space.
a=2 #Global Variable
b=3 #Local Variable
When you try to access the local variable outside the function add(), it will throw an error.
vieh_group = “Company 1”
VIEH_Group = “Company 2” print(vieh_group)
Method 1: sys.stdout.flush()
Print by default prints to sys.stdout.
Method 2: flush = True
Since Python 3.3, we have flush parameter, which can be marked as true to by default send flush the output of print command as shown
> A collection of
>An ordered list of values.
As Python supports JSON parsers, JSON-based data is actually represented as a dictionary in Python. You can convert JSON data into python using the load() function of the json module.
> isinstance(): this method checks the type of instance. Example:
isinstance(myObj, int) – returns True only when “myObj. class ” is “int”.
> issubclass(): this method checks class inheritance Example:
issubclass(bool, int) – returns True because “bool” is a subclass of “int”. issubclass(unicode, str) – returns False because “unicode” is not a subclass of “str”.
Python’s “re” module provides regular expression patterns and was introduce from later versions of Python 2.5. “re” module is providing methods for search text strings, or replacing text strings along with methods for splitting text strings based on the pattern defined.
> Open an output file in “write” mode and the print the contents into that file using the sys.stdout attribute.
filename = “outputfile” sys.stdout = open() print “testing”
> On the command line, you can redirect the output of a python script to a file. For example:
redirect_output.py has the following code:
print “Testing” execution:python redirect_output.py > outputfile
> os.path.isfile(): This method is used to check whether the give path references a file or not. It returns True if the path references to a file, else it returns false.
> os.path.isdir(): This method is used to check whether the give path references a directory or not. It returns True if the path references to a directory, else it returns false.
>os.path.getsize() Returns the size of the given file os.path.getmtime() Returns the timestamp of the given path.
> Help() will display the documentation string. It is used to see the help related to modules, keywords, and attributes, among other things. If no argument is given, the help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
> Dir() is similar to help but will not necessarily return the same results. Without arguments, it will return the list of names in the current local scope. With an argument, it attempts to return a list of valid attributes for that object. When used on an object, dir() attempts to produce the most relevant information for that object. It will not necessarily return a complete listing of information for the object.
How useful was this post?
Click to rate it!
Average rating 4.9 / 5. Vote count: 53
No votes so far! Be the first to rate this post.