Interview Questions Flashcards

1
Q

What is Python? What are the benefits of using Python

A

Python is a high-level, interpreted, general-purpose programming language. Being a general-purpose language, it can be used to build almost any type of application with the right tools/libraries. Additionally, python supports objects, modules, threads, exception-handling, and automatic memory management which help in modelling real-world problems and building applications to solve these problems.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a dynamically typed language?

A

Static - Data Types are checked before execution.
Dynamic - Data Types are checked during execution.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is PEP 8 and why is it important?

A

PEP stands for Python Enhancement Proposal. A PEP is an official design document providing information to the Python community, or describing a new feature for Python or its processes. PEP 8 is especially important since it documents the style guidelines for Python Code. Apparently contributing to the Python open-source community requires you to follow these style guidelines sincerely and strictly

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is an interpreter language

A

An Interpreted language executes its statements line by line. Languages such as Python, Javascript, R, PHP, and Ruby are prime examples of Interpreted languages. Programs written in an interpreted language runs directly from the source code, with no intermediary compilation step.

is not in machine-level code before runtime.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is Scope in Python

A

Every object in Python functions within a scope. A scope is a block of code where an object in Python remains relevant. Namespaces uniquely identify all the objects inside a program. However, these namespaces also have a scope defined for them where you could use their objects without any prefix. A few examples of scope created during code execution in Python are as follows:

A local scope refers to the local objects available in the current function.
A global scope refers to the objects available throughout the code execution since their inception.
A module-level scope refers to the global objects of the current module accessible in the program.
An outermost scope refers to all the built-in names callable in the program. The objects in this scope are searched last to find the name referenced.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are lists and tuples? What is the key difference between the two?

A

Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types. Lists are represented with square brackets [‘sara’, 6, 0.19], while tuples are represented with parantheses (‘ansh’, 5, 0.97). The key difference between the two is that while lists are mutable, tuples on the other hand are immutable objects

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is pass in Python?

A

The pass keyword represents a null operation in Python. It is generally used for the purpose of filling up empty blocks of code which may execute during runtime but has yet to be written. Without the pass statement in the following code, we may run into some errors during code execution.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are modules and packages in Python?

A

Python packages and Python modules are two mechanisms that allow for modular programming in Python. Modularizing has several advantages -

Simplicity: Working on a single module helps you focus on a relatively small portion of the problem at hand. This makes development easier and less error-prone.
Maintainability: Modules are designed to enforce logical boundaries between different problem domains. If they are written in a manner that reduces interdependency, it is less likely that modifications in a module might impact other parts of the program.
Reusability: Functions defined in a module can be easily reused by other parts of the application.
Scoping: Modules typically define a separate namespace, which helps avoid confusion between identifiers from other parts of the program.
Modules, in general, are simply Python files with a .py extension and can have a set of functions, classes, or variables defined and implemented. They can be imported and initialized once using the import statement. If partial functionality is needed, import the requisite classes or functions using from foo import bar.

Packages allow for hierarchial structuring of the module namespace using dot notation. As, modules help avoid clashes between global variable names, in a similar manner, packages help avoid clashes between module names.
Creating a package is easy since it makes use of the system’s inherent file structure. So just stuff the modules into a folder and there you have it, the folder name as the package name. Importing a module or its contents from this package requires the package name as prefix to the module name joined by a dot.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are global, protected and private attributes in Python?

A

Global variables are public variables that are defined in the global scope. To use the variable in the global scope inside a function, we use the global keyword.
Protected attributes are attributes defined with an underscore prefixed to their identifier eg. _sara. They can still be accessed and modified from outside the class they are defined in but a responsible developer should refrain from doing so.
Private attributes are attributes with double underscore prefixed to their identifier eg. __ansh. They cannot be accessed or modified from the outside directly and will result in an AttributeError if such an attempt is made.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the use of self in Python?

A

Self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. self is used in different places and often thought to be a keyword. But unlike in C++, self is not a keyword in Python

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is __init__?

A

__init__ is a contructor method in Python and is automatically called to allocate memory when a new object/instance is created. All classes have a __init__ method associated with them. It helps in distinguishing methods and attributes of a class from local variables.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is break, continue and pass in Python?

A

Break The break statement terminates the loop immediately and the control flows to the statement after the body of the loop.
Continue The continue statement terminates the current iteration of the statement, skips the rest of the code in the current iteration and the control flows to the next iteration of the loop.
Pass As explained above, the pass keyword in Python is generally used to fill up empty blocks and is similar to an empty statement represented by a semi-colon in languages such as Java, C++, Javascript, etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are unit tests in Python?

A

Unit test is a unit testing framework of Python.
Unit testing means testing different components of software separately.

Can you think about why unit testing is important? Imagine a scenario, you are building software that uses three components namely A, B, and C. Now, suppose your software breaks at a point time. How will you find which component was responsible for breaking the software? Maybe it was component A that failed, which in turn failed component B, and this actually failed the software. There can be many such combinations.
This is why it is necessary to test each and every component properly so that we know which component might be highly responsible for the failure of the software.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is docstring in Python?

A

Documentation string or docstring is a multiline string used to document a specific code segment.
The docstring should describe what the function or method does.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is slicing in Python?

A

As the name suggests, ‘slicing’ is taking parts of.
Syntax for slicing is [start : stop : step]
start is the starting index from where to slice a list or tuple
stop is the ending index or where to sop.
step is the number of steps to jump.
Default value for start is 0, stop is number of items, step is 1.
Slicing can be done on strings, arrays, lists, and tuples.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the difference between Python Arrays and lists?

A
  • Arrays in python can only contain elements of same data types i.e., data type of array should be homogeneous.
  • It is a thin wrapper around C language arrays
    consumes far less memory than lists.
  • Lists in python can contain elements of different data types i.e., data type of lists can be heterogeneous. It has the disadvantage of consuming large memory.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How is memory managed in Python?

A

Memory management in Python is handled by the Python Memory Manager. The memory allocated by the manager is in form of a private heap space dedicated to Python. All Python objects are stored in this heap and being private, it is inaccessible to the programmer. Though, python does provide some core API functions to work upon the private heap space.
Additionally, Python has an in-built garbage collection to recycle the unused memory for the private heap space.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are Python namespaces? Why are they used?

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.
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.
The lifecycle of a namespace depends upon the scope of objects they are mapped to. If the scope of an object ends, the lifecycle of that namespace comes to an end. Hence, it isn’t possible to access inner namespace objects from an outer namespace.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is Scope Resolution in Python

A

What is Scope Resolution in Python?

Sometimes objects within the same scope have the same name but function differently. In such cases, scope resolution comes into play in Python automatically. A few examples of such behavior are:

Python modules namely ‘math’ and ‘cmath’ have a lot of functions that are common to both of them - log10(), acos(), exp() etc. To resolve this ambiguity, it is necessary to prefix them with their respective module, like math.exp() and cmath.exp().
Consider the code below, an object temp has been initialized to 10 globally and then to 20 on function call. However, the function call didn’t change the value of the temp globally. Here, we can observe that Python draws a clear line between global and local variables, treating their namespaces as separate identities.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What are decorators in Python?

A

decorator function to convert to lowercase

functionality to an existing function in Python without changing the structure of the function itself. They are represented the @decorator_name in Python and are called in a bottom-up fashion. For example:

def lowercase_decorator(function):
def wrapper():
func = function()
string_lowercase = func.lower()
return string_lowercase
return wrapper
# decorator function to split words
def splitter_decorator(function):
def wrapper():
func = function()
string_split = func.split()
return string_split
return wrapper
@splitter_decorator # this is executed next
@lowercase_decorator # this is executed first
def hello():
return ‘Hello World’
hello() # output => [ ‘hello’ , ‘world’ ]
The beauty of the decorators lies in the fact that besides adding functionality to the output of the method, they can even accept arguments for functions and can further modify those arguments before passing it to the function itself. The inner nested function, i.e. ‘wrapper’ function, plays a significant role here. It is implemented to enforce encapsulation and thus, keep itself hidden from the global scope.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is lambda in Python? Why is it used?

A

Lambda is an anonymous function in Python, that can accept any number of arguments, but can only have a single expression. It is generally used in situations requiring an anonymous function for a short time period. Lambda functions can be used in either of the two ways:

Assigning lambda functions to a variable:
mul = lambda a, b : a * b
print(mul(2, 5)) # output => 10
Wrapping lambda functions inside another function:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What are generators in Python?

A

Generators are functions that return an iterable collection of items, one at a time, in a set manner.
Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is PYTHONPATH in Python?

A

PYTHONPATH is an environment variable which you can set to add additional directories where Python will look for modules and packages. This is especially useful in maintaining Python libraries that you do not wish to install in the global default location.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the use of help() and dir() functions?

A

help() function in Python is used to display the documentation of modules, classes, functions, keywords, etc. If no parameter is passed to the help() function, then an interactive help utility is launched on the console.
dir() function tries to return a valid list of attributes and methods of the object it is called upon. It behaves differently with different objects, as it aims to produce the most relevant data, rather than the complete information.

For Modules/Library objects, it returns a list of all attributes, contained in that module.
For Class Objects, it returns a list of all valid attributes and base attributes.
With no arguments passed, it returns a list of attributes in the current scope.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

How Python is interpreted?

A

Python as a language is not interpreted or compiled. Interpreted or compiled is the property of the implementation. Python is a bytecode(set of interpreter readable instructions) interpreted generally.
Source code is a file with .py extension.
Python compiles the source code to a set of instructions for a virtual machine. The Python interpreter is an implementation of that virtual machine. This intermediate format is called “bytecode”.
.py source code is first compiled to give .pyc which is bytecode. This bytecode can be then interpreted by the official CPython or JIT(Just in Time compiler) compiled by PyPy.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

How are arguments passed by value or by reference in python?

A

Pass by value: Copy of the actual object is passed. Changing the value of the copy of the object will not change the value of the original object.
Pass by reference: Reference to the actual object is passed. Changing the value of the new object will change the value of the original object.

27
Q

What are iterators in Python?

A

Iterators are objects which can be traversed through or iterated upon.

It remembers its state i.e., where it is during iteration (see code below to see how)
__iter__() method initializes an iterator.
It has a __next__() method which returns the next item in iteration and points to the next element. Upon reaching the end of iterable object __next__() must return StopIteration exception.
It is also self-iterable.
Iterators are objects with which we can iterate over iterable objects like lists, strings, etc.

28
Q

How to delete a file in Python

A

os.remove()

29
Q

Explain split and join function in python

A

You can use split() function to split a string based on a delimiter to a list of strings
You can use join() function to join a list of strings based on a delimiter to give a single string

30
Q

What does *args and **kwargs mean?

A

*args is a special syntax used in the function definition to pass variable-length arguments.
* means variable length and args is the name used by convention.
**kwargs is a special syntax used in the function definition to pass variable length keyworded arguments
Kwargs is actually a dictionary of the variable names and its value

31
Q

What are negative indexes and why are they used

A

Negative indexes are the indexes from the end of the list or tuple or string
Arr[-1] means the last element of array Arr[]

32
Q

how do you create a class in Python

A

class InterviewbitEmployee:
def __init__(self, name):
self.emp_name = emp_name

33
Q

How does inheritance work in python?

A

Inheritance gives the power to a class to access all atrributes and methods of another class. It aids in code reusability and helps the developer to maintain applications without redundant code. The class inheriting from another class is a child class or also called a derived class. The class from which a child class derives the members are called parent class or superclass

Parent class
class ParentClass:
def par_func(self):
print(“I am parent class function”)

Child class
class ChildClass(ParentClass):
def child_func(self):
print(“I am child class function”)

34
Q

How do you access parent members in the child class

A

class Parent(object):
# Constructor
def __init__(self, name):
self.name = name

class Child(Parent):
# Constructor
def __init__(self, name, age):
Parent.name = name
self.age = age

def display(self):
print(Parent.name, self.age)

35
Q

Difference between new and override modifiers

A

The new modifier is used to instruct the compiler to use the new implementation and not the base class function. The Override modifier is useful for overriding a base class function inside the child class.

36
Q

Why is finalize used

A

Finalize method is used for freeing up the unmanaged resources and clean up before the garbage collection method is invoked. This helps performing memory management tasks

37
Q

how will you check if a class is a child of another class?

A

issubclass()

38
Q

Define pandas dataframe

A

dataframe = pd.DataFrame(data, index, columns, dtype)

39
Q

how will you comninde different pandas dataframes

A

append() or df.append(df2)

40
Q

concat()

A

used to stack dataframes vertically. pd.concat([df1, df2])

41
Q

join method

A

This is used for extracting data from various dataframes having one or more common columns.
df1.join(df2)

42
Q

How will you identify and deal with missing values in a dataframe

A

missing_data_count = df.isnull().sum()
df[‘column_name].fillna(0)
df[‘column_name’] = df[‘column_name’].fillna((df[‘column_name’].mean()))

43
Q

How do you delete indices, columns and rows

A

.drop(labels=[‘column1’], axis=1, inplace=True)
axis 1 for columns and 0 for rows

44
Q

What are the key features of pythons

A
  • Python is an interpreted language
  • dynamically typed
  • Well suited for object oriented programming
  • functions are first-class objects: assigned to variable and passed into functions
  • General purpose language
45
Q

What is a decorator in python

A

Decorators are used to add some design patterns toa function without changing its structure. Generally are defined before the function they are enghancing.

46
Q

What are keywords

A

keywords in python are reserved words that have special meaning. they are generally used to define type of variables. Cannot be used for variable or function names.

47
Q

what are Literals

A

literals represents a fixed value for primitive data types.
there are 5 types:
- String literal
- character literal
- numeric literal
- boolean literals
- literal collection

48
Q

How can you randomize the items of a list in place in Python

A

from random import shuffle
x = [1,2,3,4,5]
shuffle(x)

49
Q

How can you generate random numbers in python

A

import random
random.random
randrange(a,b)

50
Q

What is the difference between range and xrange

A

xrange returns and xrange object while range returns a list object

51
Q

what is an xrange object

A

xrange creates the values as you need them with a special technique called yielding. this is use with a generator. good for billions of records.

52
Q

What is the purpose of is, not, and in operators

A

Operators are special functions.
is: checks when two variables point to the same object in memory
not: return the invers of the bolean value
in: check if some element is present in som sequence

53
Q

Ternery expression

A

[on_true] if [expression] else [on_false]

54
Q

What are the built-in types of python?

A

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

55
Q

What advantages do NumPy arrays offer over (nested) python lists

A

python lists don’t support vecotized operations like elementwise addition and multiplication.
Numpy arrays are faster and you get a lot of great functions like fast searching, basic statistics.

56
Q

What is the difference between deep and shallow copy?

A

Shallow is used when a new instance type gets created and it keeps the values that are copied in the new instance. Used to copy the reference pointers just like it copies the values. These references point to the original objects

Deep is used to store the values that are already copies. Doesn’t copy there reference pointers to the object. It makes the reference to an object and the new object that is pointed by some other object gets stored

57
Q

What is polymorphism

A

Polymorphism means the ability to take multiple forms. 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 this

58
Q

Define encapsulations in python

A

Encapsulation means binding the code and the data together. a Python class is an example of encapsulation

59
Q

Does python make use of access specifiers?

A

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

60
Q

What does an object() do?

A

It returns a featureless object that is a base for all classes. Aslo, it does not take any parameters

61
Q

Explain what flask is and its benefits

A

Flask is a web microframework for python based on “Werkseug, Jinja2 and good intentions”. It is meant to be light with little dependencies. The developer gets to choose the packages they use.

62
Q

What is the map function in python?

A

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

63
Q

Why are local variable names begining with an underscore discouraged

A

the are used to indicate a private variable of a class. They are meant to be variables in classes that must not be accessed from outside the class