Python telephonic /theory-oriented
interview questions
Python Interview questions
for freshers & Experienced
********** @@@ Interview Questions on Python Basics
@@@*************
__author__ = "Narendra
Boyina"
Note: For an interviewer no need
to answer exactly as I have written below.
I have written complete information regarding the
question.
Understand the below questions &
answers, then perform on your own in front of the interviewer.
@ All the
best for your bright future @
General Python Interview Questions & Answers:
==> How is
memory managed in Python?
- Python
memory is managed by Python's private heap space.
- All Python
objects and data structures are in a private heap.
- The programmer
does not have access to this private heap and the interpreter takes care
of this Python private heap.
- The allocation
of Python heap space for Python objects is done by the Python memory
manager.
- 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.
==> What are
Python Identifiers?
A Python identifier is a
name used to identify a variable/ function/ class/ module/ other object.
Rules for Identifiers:
·
Identifier
name purpose we can use a combination of alphabets (A to Z or a to z), digits (0to
9), an underscore (_)
·
Python
does not allow punctuation characters such as @, $, and % - + .... etc within identifiers.
·
Identifier
names should not start with numbers.
·
Keywords/
reserved words should not use as an Identifier.
·
Python
is a case-sensitive programming language.
Ex: Manpower and manpower are
two different identifiers in Python.
General information regarding identifiers:
·
Class name starts
with an uppercase letter.
·
All other
identifiers start with a lowercase letter (Ex: variable, function, method).
·
Starting an
identifier with a single leading underscore indicates that the identifier is
private (private variables/private method).
Explanation:
o
Generally, we use private variables & private methods
inside a class for Data hiding purposes.
o
Private variables are also known as hided variables.
o
Private method also known as hided methods.
o
Outside the class, you cannot access the private variables
as well as the private methods.
·
Starting an
identifier with two leading underscores indicates a strongly private
identifier.
·
If the identifier ends with two trailing underscores, the identifier is a
language-defined special name. Example: __author__ = "Narendra Boyina"
==> Mention
the use of the // operator in Python?
It is a Floor Division-operator, which is used for dividing
two operands with the result as a quotient showing only digits before the
decimal point. For instance, 10//5 = 2 and 10.0//5.0 = 2.0.
==> What are the built-in Data types available in Python, classify them as either Homogeneous or Heterogeneous & classify them as mutable or immutable.
or
What are the data structures /data types available in
Python?
Immutable built-in types
Numbers
------> Ex:
123
-------> Homogeneous
Strings
------>
Ex: "Narendra "
------>
Homogeneous
Tuples
------> Ex:
(1, "Narendra", 1.5)
------> Heterogeneous
Mutable built-in types
List
------> Ex: [1,
"Narendra", 1.5] ------> Heterogeneous
Set
------>
Ex: {1, "Narendra", 1.5}
------> Heterogeneous
Dictionary -----> Ex: {'Name':'Narendra', 'Age':26, 'Percentage':76.2, 1990:'birthday'}
where
the key is immutable & unique.
The value may be mutable/ immutable (Heterogeneous)
==> What is the difference between List and Tuple?
List and Tuple both are Heterogeneous
which means we can be able to store more than one value in a single variable.
List is a mutable sequence; we can modify
list elements.
Tuple is an immutable sequence; we
can’t perform modifications on tuple.
==> What are the modifications you can perform on the list?
List is a super dynamic and mutable sequence. We can add, and delete elements by using append, extend, and remove functions.
==> Can we perform modifications on the tuple?
No: Tuple is an immutable sequence, i.e.
we cannot perform operations like list.
==> What is the difference
between a list, tuple, and set?
list
[], tuple (), and set {} are heterogeneous data structures/ Data types.
list
& set are mutable, but the tuple is immutable.
==>
What is the difference between append and extend?
append function
will add a single element at the end of the List.
Extend function
will add multiple elements at the end of the List.
==>What
is the difference between Dictionary and Set?
Dictionary is a key value pair.
Dictionary is an
unordered mapping from unique.
immutable
key to mutable/immutable values.
No
duplicate key is allowed in a dictionary.
Optional:
when duplicate keys occur during an assignment the last assignment wins.
Set is
an Unordered collection of unique data.
Delimited
by {curly braces} filled with comma-separated values.
==>What
is the difference between Deep copy and shallow copy?
Deep
copy creates a separate memory location.
While
copying a list to another variable, if we use deep copy, it creates a separate
memory location for the 2nd list.
so, if you change an element in the 2nd list, the 1st list will
not be changed.
Shallow
copy uses the same memory location.
While
copying a list to another variable, if we use shallow copy, it uses the same memory location
for the 2nd list.
If you
change an element in the 2nd list, then 1st list values also
will change.
==> Define
Conditional /Decision-making statement?
It will
execute based on the given condition of the expression.
Types: if statement, if else, if elif else and nested if statement.
==> Control
flow statements or iterative statements
for
loop: Executes a set of elements repeatedly, depending on the
number of elements in a sequence.
While
loop: Executes a set of elements repeatedly until the condition fails.
==>Define
Break and continue statements?
Break keyword will cause your for-loop to stop executing and exit without
reaching the
end of
the list or end of the function.
Continue
statement: we can use this to skip the current iteration and
continue the next iteration
==> What is
Function?
A function is a block of organized code that is used to perform single/ multiple
actions.
The purpose of the
function is code re-usability.
Once the basic structure of a function
is finalized. You can execute it by calling from another function also.
==> Types of
Functions?
There
are two types of functions 1. Recursive function 2. Non-recursive
functions
We
have 6 types of non-recursive functions:
1. function without arguments
2. functions with arguments/ positional/ Required arguments
3. functions with Default arguments
4. functions with Variable-length arguments (* args)
5. functions with Keyword arguments (**args) / (**kw args)
6. functions with command line arguments
==> What is variable-length
arguments/ *args in python?
Variable-length arguments are defined using
the *args and var_args for short,
arguments that can take Zero args/ an unspecified amount of
input args and
store those arguments in a tuple.
or
*args can take Zero
values or any number of values in it.
and no values are passed to it then also it will not give
any error.
==> What is Keyword arguments/
**args/kw_args in python?
Python can accept multiple keyword arguments, it is
also known as **kwargs.
It behaves similarly to *args, but stores the
arguments in a dictionary.
or
**kwargs can take Zero key_based values or any number of
key_based values in it.
and no key_based values are passed to it then also it will
not give any error.
==> What is comprehension and what are the different types of comprehension in Python?
Comprehensions
in Python provide us with a short way to construct new sequences
(such as lists, sets, dictionaries, etc.) using sequences that have been already defined.
Advantages of using Comprehensions
- No need to declare an empty list/set/dictionary.
- No need to write an append method, Comprehension will take care of both.
Comprehensions are syntax constructions to
ease the creation of a Dictionary or List based on existing iterable.
List
Comprehensions provide an elegant way to create new lists.
Syntax: Variable = [expression(element)
for element in iterable]
Ex: list_1 = ["Always", "Trust
yourself", "Do", Hard-work", "You",
"can", "reach", "your","goals",
"easily"]
x = [((len(i)) *3) for i in list_1]
# It calculates the length of each word & length multiplied
by 3 then the result is stored in the same list instead of taking a new empty list and
appending the result
print(x) # [18, 42, 6, 27, 9, 9, 15, 12, 15, 18]
Set Comprehensions
Syntax: Variable = {expression(item) for
item in iterable}
set function eliminates duplicate objects present if any
result set will not store in order because the set is unordered.
from math import factorial
f = {len(str(factorial(x))) for x in range (20)}
print(f) # length of factorial of numbers till 19
# Result : set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14,
15, 16, 18])
# Note: duplicate elements were discarded because of set
comprehension
Dictionary
Comprehensions
Syntax: Variable = {key_expr :
value_expr for item in iterable}
Ex: Naren = [1,2,3,4]
x = {i: i**i for i in Naren} # dictionary comprehension
print(x)
# Output {1: 1, 2: 4, 3: 27, 4: 256}
==> What is lambda in Python
and what is the drawback of lambda?
Lambda function is a single-line anonymous function
but not declared in the standard manner by using the “def” keyword.
Drawback: lambda function allows
multiple arguments in it but can return only one return value
in the form of an expression.
==>Define Map( ) and filter( )
map() will apply the same function to
every element of iterable /sequence and return a list of the results.
The filter(function_name, iterable) function offers a way, to filter out all the elements of a list, for which the function
returns True.
==>Difference between read(), readline() and
readlines() functions?
read(n) : Reads at most n characters
from the file. Reads till the end of file
deadline() : Reads and returns
one line from the file.
readlines() : Reads and returns a list
of lines from the file.
==> What is Class?
Class is nothing but just blue-print and there is no use of
class definition,
unless you have
created the instance/object for that class.
==> What are the advantages of classes compared with functions?
- We can provide a specific class name by grouping functions in the form of methods
- We can inherit the class into another class.
- We can perform multiple class-related properties
(single/multiple/hybrid inheritances, Data hiding/abstraction/ method overriding / encapsulation...)
==> Difference between method
and function?
A function that is defined inside of the class is a method.
A function that is defined outside of the class is a
Function.
==> What is the _ _init_ _ ()
method or Constructor method?
Constructor method (def __init__(self)) is a special kind
of method,
as soon as you have created an object/ instance for the
class then automatically,
_ _init_ _
method will be executed, without calling it.
==> What is the difference between the class variable and the instance variable?
Class
variables can use in all instances of the same class created by the user.
class
variables, which have the same value across all class instances (i.e., static
variables)
Instance
variables can use only for the same instance.
Instance
variables are owned by instances of the class. T
this means that
for each object or instance of a class, the instance variables are different.
· Class variables will be shared among the
multiple instances of the class.
· But the instance variable will be independent.
· Class variables are defined within the
class but outside of the class method.
· Class variables are not used as frequently
as instance variables.
==> What are
pass, continue & Assert keywords in Python?
Pass means,
a no-operation Python statement, or in other words, it is a placeholder in a
compound statement, where there should be a blank left and nothing has to be
written there.
Python's assert statement
is a debugging aid that tests a condition.
If the condition is true, it does
nothing and your program just continues to execute.
But if the assert condition evaluates
to false, it raises an AssertionError exception with an optional error message.
x = "narendra"
#if the condition returns
False, AssertionError is raised:
assert
x == "Narendra", "x
should be 'narendra'"
==> In
Python what are iterators and generators?
Iterators are used to iterate a group
of elements, containers like list.
The way of implementing iterators is
known as generators.
The generator function is
normal, except that it yields expression in the function.
==>What are Python namespaces? Why are they used?
Scope in Python
A namespace in Python ensures that
object names in a program are unique and can be used without any conflict.
Python implements these namespaces as dictionaries with 'name as key' mapped to
a corresponding 'object as value'. This allows for multiple namespaces to use
the same name and map it to a separate object. A few examples of namespaces are
as follows:
·
Local Namespace includes
local names inside a function. the namespace is temporarily created for a
function call and gets cleared when the function returns. Examples :
narendra =30, x = 40, y =50 defined inside functions
·
Global Namespace includes
names from various imported packages/ modules that are being used in the
current project. This namespace is created when the package is imported in the
script and lasts until the execution of the script.
·
Built-in Namespace includes
built-in functions of core Python and built-in names for various types of
exceptions. Examples: print(), id(), type(), len(), input()
==> What is a module?
Python module is nothing but a
Python file.
That filename is referred to as the module name while importing
to another
==> Purpose of a module?
For using the functions, class methods are defined in
another file in the current Python file.
We are having 3 types of modules in Python
1. User-defined
modules (we need to create these modules)
2. Internal modules (During
the installation of the Python these modules will be installed)
3. External modules
(We need to install these modules)
==> What internal &
external modules do you know?
Internal Modules: datetime, time,
calendar, random, os, sys, re, json string
External Modules: openpyxl, paramiko,
serial, subprocess
==>Tell the
different ways of utilizing modules in your code?
we can use modules in 17 ways. Refer to my training notes for an answer
==> Mention what are the rules
for local and global variables in Python?
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.
==> What is
the module and package in Python?
In Python, a module is a way to
structure a program. Each Python program file is a module, which imports other
modules like objects and attributes.
The folder of the Python program is a
package of modules. A package can have modules or subfolders.
If a folder contains __init__
(constructer) then it is a package (it may be an empty constructer) otherwise,
it is just a folder.
==> How can
you share global variables across modules?
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.
==> Explain
how you can make a Python Script executable on Unix?
To make a Python Script executable on Unix, you need
to do 2 things:
·
Script file's mode
must be executable and
·
Inside python
file the first line must begin with # ( #!/usr/local/bin/python)
==> What is Comprehension?
Comprehensions in Python provide us with a short way to
construct new sequences
(such as lists, sets,
dictionaries, etc.) using sequences that have been already defined.
Advantages
of Comprehension
we do not need to declare an empty list/set/dictionary.
We do not need to write an append method, Comprehensions
will take care
Python
supports the following 3 types of comprehension:
·
List Comprehensions
·
Dictionary
Comprehensions
·
Set Comprehensions
==> What are Python decorators?
A Python decorator is a specific change
that we make in Python syntax to alter functions easily.
==> what is "chmod 777" ?
chmod
777 means granting all permissions to read, write, and to execute any
file by any user of the system
chmod 777 -R
Dir_name (Note: -R means
recursive Change files and directories recursively)
Request: Please provide your valuable comments