Python Questions For Interview With Answers 2021
This Best Python Questions For Interview with answers 2020 is a great help for those students and professionals who are preparing for Job Interview and exam certification.
Python Questions For Interview With Answers 2020
- Python Questions For Interview: What is Python? What are the benefits of using Python?
Answer: Python is a programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source.
- Python Questions For Interview: What is PEP 8?
Answer: PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable.
- Python Questions For Interview: What is pickling and unpickling?
Answer: 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.
- Python Questions For Interview: How Python is interpreted?
Answer: Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.
- Python Questions For Interview: What are the tools that help to find bugs or perform static analysis?
Answer: PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.
- Python Questions For Interview: What are Python decorators?
Answer: A Python decorator is a specific change that we make in Python syntax to alter functions easily.
- Python Questions For Interview: What is the difference between list and tuple?
Answer: The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries.
- Python Questions For Interview: How are arguments passed by value or by reference?
Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result you cannot change the value of the references. However, you can change the objects if it is mutable.
- Python Questions For Interview: What is Dict and List comprehensions are?
Answer: They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.
Python Questions For Interview: They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable. - Python Questions For Interview: What are the built-in type does python provides?
Answer: There are mutable and Immutable types of Pythons built in types Mutable built-in types
List
Sets
Dictionaries
Immutable built-in types
Strings
Tuples
Numbers
In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object.
It is a single expression anonymous function often used as inline function.
A lambda form in python does not have statements as it is used to make new function object and then return them at runtime.
Pass means, no-operation Python statement, or in other words it is a place holder in compound statement, where there should be a blank left and nothing has to be written there.
In Python, iterators are used to iterate a group of elements, containers like list.
A unit testing framework in Python is known as unit test. It supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections etc.
A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known as slicing.
The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function.
A Python documentation string is known as docstring, it is a way of documenting Python functions, modules and classes.
To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general case. You cannot copy all objects but most of them.
Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth.
In order to convert a number into a string, use the inbuilt function str(). If you want a octal or hexadecimal representation, use the inbuilt function oct() or hex().
Xrange returns the xrange object while range returns the list, and uses the same memory and no matter what the range size is.
In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes.
The folder of Python program is a package of modules. A package can have modules or subfolders.
Local variables: If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be local.
Global variables: Those variables that are only referenced inside a function are implicitly global.
To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.
To make a Python Script executable on Unix, you need to do two things,
Script file’s mode must be executable and the first line must begin with # ( #!/usr/local/bin/python).
By using a command os.remove (filename) or os.unlink(filename)
30) Explain how can you generate random numbers in Python?
To generate random numbers in Python, you need to import command as
import random random.random()
This returns a random floating point number in the range [0,1)
You can access a module written in Python from C by following method,
Module = =PyImport_ImportModule(“”);
It is a Floor Divisionoperator , which is used for dividing two operands with the result as quotient showing only digits before the decimal point. For instance, 10//5 = 2 and 10.0//5.0 = 2.0.
Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc.
Python does not require explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically Provide easy readability due to use of square brackets.
Easy-to-learn for beginners. Having the built-in data types saves programming time and effort from declaring variables.
The use of the split function in Python is that it breaks a string into shorter strings using the defined separator. It gives a list of all words present in the string.
Flask is a web micro framework for Python based on “Werkzeug, Jinja 2 and good intentions” BSD licensed. Werkzeug and jingja are two of its dependencies.
Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries. It makes the framework light while there is little dependency to update and less security bugs.
Flask is a “microframework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use.
Pyramid are build for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.
Like Pyramid, Django can also used for larger applications. It includes an ORM.
A session basically allows you to remember information from one request to another. In a flask, it uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.
Basically, Flask is a minimalistic framework which behaves same as MVC framework. So MVC is a perfect fit for Flask.
The data in the failed server won’t get removed, but there is a provision for auto-failure, which you can configure for multiple nodes. Fail-over can be triggered during any kind of socket or Memcached server level errors and not during normal client errors like adding an existing key, etc.
Dogpile effect is referred to the event when cache expires, and websites are hit by the multiple requests made by the client at the same time. This effect can be prevented by using semaphore lock. In this system when value expires, first process acquires the lock and starts generating new value.
Memcached common misuse is to use it as a data store, and not as a cache
Never use Memcached as the only source of the information you need to run your application. Data should always be available through another source as well
Memcached is just a key or value store and cannot perform query over the data or iterate over the contents to extract information
Memcached does not offer any form of security either in encryption or authentication.
Python is capable of scripting, but in general sense, it is considered as a general-purpose programming language. To know more about Scripting, you can refer to the Python Scripting Tutorial.
An interpreted language is any programming language which is not in machine level code before runtime. Therefore, Python is an interpreted language.
A namespace is a naming system used to make sure that names are unique to avoid naming conflicts.
It is an environment variable which is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load.
Answer: Python modules are files containing Python code. This code can either be functions classes or variables. A Python module is a .py file containing executable code.
Some of the commonly used built-in modules are:
os
sys
math
random
data time
JSON
Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program.
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.
Yes. Python is a case sensitive language.
Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc is specified within an indented block. It is usually done using four space characters. If your code is not indented necessarily, it will not execute accurately and will throw errors as well.
Arrays and lists, in Python, have the same way of storing data.
Arrays can hold only a single data type elements whereas lists can hold any data type elements
init is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the init method.
Self is an instance or an object of a class. In Python, this is explicitly included as the first parameter. However, this is not the case in Java where it’s optional. It helps to differentiate between the methods and attributes of a class with local variables.
The self variable in the init method refers to the newly created object while in other methods, it refers to the object whose method was called.
Break allows loop termination when some condition is met and the control is transferred to the next statement.
Continue Allows skipping some part of a loop when some specific condition is met and the control is transferred to the beginning of the loop
Pass Used when you need some block of code syntactically, but you want to skip its execution. This is basically a null operation. Nothing happens when this is executed.
[::-1] is used to reverse the order of an array or a sequence.
Iterators are objects which can be traversed though or iterated upon.
Random module is the standard module that is used to generate a random number.
Comments in Python start with a # character. However, alternatively at times, commenting is done using docstrings(strings enclosed within triple quotes).
Example:
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.
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.
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.
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.
Dir() function: The dir() function is used to display the defined symbols.
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.
It is impossible to de-allocate those portions of memory that are reserved by the C library.
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.
It is used to determine the length of a string, a list, an array, etc.
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.
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.
Built-in types in Python are as follows –
Integers
Floating-point
Complex numbers
Strings
Boolean
Built-in functions
Elements can be added to an array using the append(), extend() and the insert (i,x) functions.
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.
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 procedural as well as structural language.
Python libraries are a collection of Python packages. Some of the majorly used python libraries are – Numpy, Pandas, Matplotlib, Scikit-learn and many more.
The split() method is used to separate a given string in Python.
Modules can be imported using the import keyword. You can import modules in three ways.
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
Class in Python is created using the class keyword.
In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time.
Multiple inheritance means that a class can be derived from more than one parent classes. Python does support multiple inheritance, unlike Java.
Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism.
Encapsulation means binding the code and the data together. A Python class in an example of encapsulation.
Data Abstraction is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using interfaces and abstract classes.
Python does not deprive access to an instance variable or function. Python lays down the concept of prefixing the name of the variable, function or method with a single or double underscore to imitate the behavior of protected and private access specifiers.
An empty class is a class that does not have any code defined within its block. It can be created using the pass keyword. However, you can create objects of this class outside the class itself. IN PYTHON THE PASS command does nothing when its executed. it’s a null statement.
It returns a featureless object that is a base for all classes. Also, it does not take any parameters.
Flask is a “microframework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use.
Pyramid is built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.
Django can also be used for larger applications just like Pyramid. It includes an ORM.
Django MVT Pattern:
Django Architecture – Python Interview Questions – EdurekaFigure: Python Interview Questions – Django Architecture
The developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user.
You can use the command edit mysite/setting.py, it is a normal python module with module level representing Django settings.
Django uses SQLite by default; it is easy for Django users as such it won’t require any other type of installation. In the case your database choice is different that you have to the following keys in the DATABASE ‘default’ item to match your database connection settings.
Engines: you can change the database by using ‘django.db.backends.sqlite3’ , ‘django.db.backeneds.mysql’, ‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.oracle’ and so on
Name: The name of your database. In the case if you are using SQLite as your database, in that case, database will be a file on your computer, Name should be a full absolute path, including the file name of that file.
If you are not choosing SQLite as your database then settings like Password, Host, User, etc. must be added.
Django uses SQLite as a default database, it stores data as a single file in the filesystem. If you do have a database server—PostgreSQL, MySQL, Oracle, MSSQL—and want to use it rather than SQLite, then use your database’s administration tools to create a new database for your Django project. Either way, with your (empty) database in place, all that remains is to tell Django how to use it. This is where your project’s settings.py file comes in.
Django MVT Pattern:
Django Architecture – Python Interview Questions – EdurekaFigure: Python Interview Questions – Django Architecture
The developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user.
The template is a simple text file. It can create any text-based format like XML, CSV, HTML, etc. A template contains variables that get replaced with values when the template is evaluated and tags (% tag %) that control the logic of the template.
Django Template – Python Interview Questions – EdurekaFigure: Python Interview Questions – Django Template
Django provides a session that lets you store and retrieve data on a per-site-visitor basis. Django abstracts the process of sending and receiving cookies, by placing a session ID cookie on the client side, and storing all the related data on the server side.
Map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given. #Follow the link to know more similar functions.
We use python numpy array instead of a list because of the below three reasons:
Less Memory
Fast
Convenient
For more information on these parameters, you can refer to this section – Numpy Vs List.
Like 2D plotting, 3D graphics is beyond the scope of NumPy and SciPy, but just as in the 2D case, packages exist that integrate with NumPy. Matplotlib provides basic 3D plotting in the mplot3d subpackage, whereas Mayavi provides a wide range of high-quality 3D visualization features, utilizing the powerful VTK engine.
Multiple Choice Questions (MCQ)
When no exception occurs.
They are used to indicate a private variable of a class
As Python has no concept of private variables, leading underscores are used to indicate variables that must not be accessed from outside the class.
Following are some of the salient features of python −
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building large applications.
It provides very high-level dynamic data types and supports dynamic type checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
PYTHONPATH – It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer.
PYTHONSTARTUP – It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH.
PYTHONCASEOK − It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.
PYTHONHOME − It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.
Python has five standard data types −
Numbers
String
List
Tuple
Dictionary
It will print complete string. Output would be Hello World!.
It will print first character of the string. Output would be H.
It will print characters starting from 3rd to 5th. Output would be llo.
It will print characters starting from 3rd character. Output would be llo World!.
It will print string two times. Output would be Hello World!Hello World!.
It will print concatenated string. Output would be Hello World!TEST.
It will print complete list. Output would be [‘abcd’, 786, 2.23, ‘john’, 70.200000000000003].
It will print elements starting from 2nd till 3rd. Output would be [786, 2.23].
It will print elements starting from 3rd element. Output would be [2.23, ‘john’, 70.200000000000003].
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are − Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.
Python’s dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).
dict = {}
dict[‘one’] = “This is one”
dict[2] = “This is two”
tinydict = {‘name’: ‘Wong’,’code’:6734, ‘dept’: ‘sales’}
Using dictionary.keys() function, we can get all the keys from the dictionary object.
print dict.keys() # Prints all the keys
Using dictionary.values() function, we can get all the values from the dictionary object.
print dict.values() # Prints all the values
int(x [,base]) – Converts x to an integer. base specifies the base if x is a string.
long(x [,base] ) – Converts x to a long integer. base specifies the base if x is a string.
float(x) − Converts x to a floating-point number.
str(x) − Converts object x to a string representation.
repr(x) − Converts object x to an expression string.
eval(str) − Evaluates a string and returns an object.
tuple(s) − Converts s to a tuple.
list(s) − Converts s to a list.
set(s) − Converts s to a set.
dict(d) − Creates a dictionary. d must be a sequence of (key,value) tuples.
frozenset(s) − Converts s to a frozen set.
chr(x) − Converts an integer to a character.
unichr(x) − Converts an integer to a Unicode character.
ord(x) − Converts a single character to its integer value.
hex(x) − Converts an integer to a hexadecimal string.
oct(x) − Converts an integer to an octal string.
** Exponent − Performs exponential (power) calculation on operators. a**b = 10 to the power 20 if a = 10 and b = 20.
// Floor Division − The division of operands where the result is the quotient in which the digits after the decimal point are removed.
Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. x is y, here is results in 1 if id(x) equals id(y).
not in − Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. x not in y, here not in results in a 1 if x is not a member of sequence y.
break statement − Terminates the loop statement and transfers execution to the statement immediately following the loop.
Continue statement − Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
Pass statement − The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.
choice(seq) − Returns a random item from a list, tuple, or string.
randrange ([start,] stop [,step]) − returns a randomly selected element from range(start, stop, step).
random() − returns a random float r, such that 0 is less than or equal to r and r is less than 1.
seed([x]) − Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None.
shuffle(lst) − Randomizes the items of a list in place. Returns None.
isalnum() − Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
isdigit() − Returns true if string contains only digits and false otherwise.
islower() − Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
isnumeric() − Returns true if a unicode string contains only numeric characters and false otherwise.
isspace() − Returns true if string contains only whitespace characters and false otherwise.
istitle() − Returns true if string is properly “titlecased” and false otherwise.
isupper() − Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
join(seq) − Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.
len(string) − Returns the length of the string.
ljust(width[, fillchar]) − Returns a space-padded string with the original string left-justified to a total of width columns.
lower() − Converts all uppercase letters in string to lowercase.
lstrip() − Removes all leading whitespace in string.
max(str) − Returns the max alphabetical character from the string str.
min(str) − Returns the min alphabetical character from the string str.
replace(old, new [, max]) − Replaces all occurrences of old in string with new or at most max occurrences if max given.
strip([chars]) − Performs both lstrip() and rstrip() on string.
swapcase() − Inverts case for all letters in string.
How will you get titlecased version of string?
title() − Returns “titlecased” version of string, that is, all words begin with uppercase and the rest are lowercase.
upper() − Converts all lowercase letters in string to uppercase.
isdecimal() − Returns true if a unicode string contains only decimal characters and false otherwise.
To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know.
3
[1, 2, 3, 4, 5, 6]
[‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’]
3, Offsets start at zero.
1, Negative: count from the right.
cmp(list1, list2) − Compares elements of both lists.
len(list) − Gives the total length of the list.
max(list) − Returns item from the list with max value.
min(list) − Returns item from the list with min value.
list.index(obj) − Returns the lowest index in list that obj appears.
list.insert(index, obj) − Inserts object obj into list at offset index.
list.pop(obj=list[-1]) − Removes and returns last object or obj from list.
list.remove(obj) − Removes object obj from list.
list.reverse() − Reverses objects of list in place.
list.sort([func]) − Sorts objects of list, use compare func if given.
Stub.
Stack.
Yes.
No
There are some modules and functions in python that can only run on certain platforms.
Yes
Yes it has a complier which works automatically so we don’t notice the compiler of python.
Django (Web framework of Python).
Micro Frame work such as Flask and Bottle.
Plone and Django CMS for advanced content Management.
Jython
(Jython is successor of Jpython.)
No
Yes.
No.
The yield keyword can turn any function into a generator. It works like a standard return keyword. But it’ll always return a generator object. Also, a method can have multiple calls to the yield keyword.
A block begins when the line is intended by 4 spaces.
Scikit-learn python Library used for Machine learning
Pass indicates that nothing is to be done i.e. it signifies a no operation.
Pylint and pychecker.
list.pop(obj=list[-1]):
Here, −1 represents the last element of the list. Hence, the pop() function removes the last object (obj) from the list.list.pop(obj=list[-1]):
To access an element from ordered sequences, we simply use the index of the element, which is the position number of that particular element. The index usually starts from 0, i.e., the first element has index 0, the second has 1, and so on.
When we use the index to access elements from the end of a list, it’s called reverse indexing. In reverse indexing, the indexing of elements starts from the last element with the index number ‘−1’. The second last element has index ‘−2’, and so on. These indexes used in reverse indexing are called negative indexes.
We can get the indices of N maximum values from a NumPy array using the below code:
import numpy as np
ar = np.array([1, 3, 2, 4, 5, 6])
print(ar.argsort()[-3:][::-1])
Interested in learning Python? Check out this Python Training in Sydney!
Python, using the ‘with’ statement, we can open a file and close it as soon as the block of code, where ‘with’ is used, exits. In this way, we can opt for not using the close() method.
with open(“filename”, “mode”) as file_var:
Indentation in Python is compulsory and is part of its syntax.
All programming languages have some way of defining the scope and extent of the block of codes; in Python, it is indentation. Indentation provides better readability to the code, which is probably why Python has made it compulsory.
To display the contents of a file in reverse, the following code can be used:
for line in reversed(list(open(filename.txt))):
print(line.rstrip())
f= open(“hello.txt”, “wt”)
Tkinter is an in-built Python module that is used to create GUI applications. It is Python’s stand
ard toolkit for GUI development. Tkinter comes with Python, so there is no installation needed. We can start using it by importing it in our script.
Control flow statements are used to manipulate or change the execution flow of a program. Generally, the flow of the execution of a program runs from top to bottom, but certain statements (control flow statements) in Python can break this top-to-bottom order of execution. Control flow statements include decision-making, looping, and more.
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
Python lets users include a description (or quick notes) for their methods using documentation strings or docstrings. Docstrings are different from regular comments in Python as, rather than being completely ignored by the Python Interpreter like in the case of comments, Python documentation strings can actually be accessed at the run time using the dot operator when docstring is the first statement in a method or function.
No. Python is a dynamically typed language, I.E., Python Interpreter automatically identifies the data type of a variable based on the type of value assigned to the variable.
We can read a random line in a file using the random module.
For example:
import random
def read_random(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)
print(read_random (‘hello.txt’))
Enlisted below are some of the benefits of using Python.
Application development is faster and easy.
Extensive support of modules for any kind of application development including data analytics/machine learning/math-intensive applications.
Yes. It does allow to code is a structured as well as Object-oriented style. It offers excellent flexibility to design and implement your application code depending on the requirements of your application.
PIP is an acronym for Python Installer Package which provides a seamless interface to install various Python modules. It is a command line tool which can search for packages over the internet and install them without any user interaction.
You just need to install Python software and using PIP, you can install various Python modules from the open source community.
For IDE, Pycharm is highly recommended for any kind of application development with vast support for plugins. Another basic IDE is called a RIDE and is a part of the Python Python Questions For Interview: open source community.
The best and easiest way is to use ‘unittest’ python standard library to test units/classes. The features supported are very similar to the other unit testing tools such as JUnit, TestNG.
For loop is generally used to iterate through the elements of various collection types such as List, Tuple, Set, and Dictionary.
While loop is the actual looping feature that is used in any other programming language. This is how Python differs in handling loops from the other programming languages.
In Python, there is no need to define a variable’s data type explicitly.
Based on the value assigned to a variable, Python stores the appropriate data type. In the case of numbers such as Integer, Float, etc, the length of data is unlimited.
Python does not support Arrays. However, you can use List collection type which can store an unlimited number of elements.
Python has built-in support to parse strings using Regular expression module. Import the module and use the functions to find a sub-string, replace a part of a string, etc.
MySQL (Structured) and MongoDB (Unstructured) are the prominent databases that are supported natively in Python. Import the module and start using the functions to interact with the database.
As Python is an interpreter, it starts reading the code from the source file and starts executing them.
However, if you want to start from the main function, you should have the following special variable set in your source file as:
if__name__== “main
main()
Networking, Mathematics, Cryptographic services, Internet data handling, and Multi-threading modules are prominent modules. Apart from these, there are several other modules that are available in the Python developer community.
Time module can be used to calculate the time at different stages of your application and use the Logging module to log data to a file system in any preferred format.
Python has a built-in module called sub-process. You can import this module and either use run() or Popen() function calls to launch a sub-process and get the control of its return code.
We should use the threading module to implement, control and destroy threads for parallel execution of the server code. Locks and Semaphores are available as synchronization objects to manage data between different threads.
Garbage collection is an in-built feature in Python which takes care of allocating and de-allocating memory. This is very similar to the feature in Java.
Yes. As long as you have the Python environment on your target platform (Linux, Windows, Mac), you can run the same code.
Python along with standard library Tkinter can be used to create GUI based applications. Tkinter library supports various widgets which can create and handle events which are widget specific.
This is one of the string methods which removes leading/trailing white space.
There are 2 types of membership operators in Python:
in: If the value is found in a sequence, then the result becomes true else false
not in: If the value is not found in a sequence, then the result becomes true else false
currenttime= time.localtime(time.time())
print (“Current time is”, currenttime)
Output: on Language
print dict.keys()
help () is a built-in function that can be used to return the Python documentation of a particular object, method, attributes, etc.
dir () displays a list of attributes for the objects which are passed as an argument. If dir() is without the argument then it returns a list of names in current local space.
Monkey Patching refers to the modification of a module at run-time.
The group of individual statements, thereby making a logical block of code is called suites
Example:
If expression
Suite
Else
Suite
From statement allows specific attributes to be imported from a module in a current namespace.
Syntax: from modname import name1[, name2[, … nameN]]
Assert statement is used to evaluate the expression attached. If the expression is false, then python raised AssertionError Exception.
Match checks for the match at the beginning of the string whereas search checks for the match anywhere in the string.
Shallow copy is used when a new instance type gets created and it keeps values that are copied whereas deep copy stores values that are already copied.
A shallow copy has faster program execution whereas deep coy makes it slow.
Pass statement
Literals can be defined as a data which is given in a variable or constant. Python supports the following literals:
String Literals
String literals are formed by enclosing text in the single or double quotes. For example, string literals are string values.
Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable, convert into iterator and aggregates the elements based on iterables passed. It returns an iterator of tuples.
Python’s constructor: init_ () is the first method of a class. Whenever we try to instantiate an object init() is automatically invoked by python to initialize members of an object. We can’t overload constructors or methods in Python. It shows an error if we try to overload.
To remove leading characters from a string, we can use lstrip() function. It is Python string function which takes an optional char type parameter. If a parameter is provided, it removes the character. Otherwise, it removes all the leading spaces from the string.
The join() is defined as a string method which returns a string value. It is concatenated with the elements of an iterable. It provides a flexible way to concatenate the strings.
The Python provides libraries/modules that enable you to manipulate text files and binary files on the file system. It helps to create files, update their contents, copy, and delete files. The libraries are os, os.path, and shutil.
Here, os and os.path – modules include a function for accessing the filesystem
while shutil – module enables you to copy and delete the files.
In Python 3, the old Unicode type has replaced by “str” type, and the string is treated as Unicode by default. We can make a string in Unicode by using art.title.encode(“utf-8”) function.
You have to define an alias for the base class, assign the real base class to it before your class definition, and use the alias throughout your class. You can also use this method if you want to decide dynamically (e.g., depending on availability of resources) which base class to use.
The shortest way to open a text file is by using “with” command in the following manner:
The enumerate() function is used to iterate through the sequence and retrieve the index position and its corresponding value at the same time.
The output will be [‘!!Welcome!! ‘, ‘!!Welcome!!’]
The pass statement is a null operation. Nothing happens when it executes. You should use “pass” keyword in lowercase. If you write “Pass,” you’ll face an error like “NameError: name Pass is not defined.” Python statements are case sensitive.
You can use PyChecker, which is a static analyzer. It identifies the bugs in Python project and also reveals the style and complexity related bugs.
Another tool is Pylint, which checks whether the Python module satisfies the coding standard.
Lambda Vs. Def.
Def can hold multiple expressions while lambda is a uni-expression function.
Def generates a function and designates a name to call it later. Lambda forms a function object and returns it.
Def can have a return statement. Lambda can’t have return statements.
Lambda supports to get used inside a list and dictionary.
No, Python does not have a Switch statement, but you can write a Switch function and then use it.
Python has support for formatting any value into a string. It may contain quite complex expressions.
One of the common usages is to push values into a string with the %s format specifier. The formatting operation in Python has the comparable syntax as the C function printf() has.
Python strings are indeed immutable
Let’s take an example. We have an “str” variable holding a string value. We can’t mutate the container, i.e., the string, but can modify what it contains that means the value of the variable.
A function in Python gets treated as a callable object. It can allow some arguments and also return a value or multiple values in the form of a tuple. Apart from the function, Python has other constructs, such as classes or the class instances which fits in the same category.
The Python trunc() function performs a mathematical operation to remove the decimal values from a particular expression and provides an integer value as its output.
The continue is a jump statement in Python which moves the control to execute the next iteration in a loop leaving all the remaining instructions in the block unexecuted.
The continue statement is applicable for both the “while” and “for” loops.
Python’s print() function always prints a newline in the end. The print() function accepts an optional parameter known as the ‘end.’ Its value is ‘\n’ by default. We can change the end character in a print statement with the value of our choice using this parameter.
Python provides this built-in isalpha() function for the string handling purpose.
It returns True if all characters in the string are of alphabet type, else it returns False.
PyPy provides maximum compatibility while utilizing CPython implementation for improving its performance.
The tests confirmed that PyPy is nearly five times faster than the CPython. It currently supports Python 2.7.
Python supports GIL (the global interpreter lock) which is a mutex used to secure access to Python objects, synchronizing multiple threads from running the Python bytecodes at the same time.
Related Article
- SQL Questions for Interview with Answers 2020
- PHP Questions For Interview With Answers 2020
- Java Questions For Interview With Practical Answers 2020
- SEO Questions for Interview with Answers 2020
Inquiries
If You have any questions or suggestions about Python Questions For Interview with Answers 2020, please feel free to leave a comment below.
Thank you for sharing.
Great post!