80 Q and A Data Science
80 Q and A Data Science
You have 2 free stories left this month. Sign up and get an extra one for free.
Many Data Aspirant started learning their Data Science journey with Python
Programming Language. Why Python? because it was easy to follow and many
companies use Python programming language these days. Moreover, Python is a
multi-purpose language that not specific only for Data scientists; people also use
Python for developer purposes.
When you applying for a position as a Data Scientist, many companies would need
you to follow a job inter view with the Python knowledge. In this case, I tr y to outline
the Python Inter view question I collected from many sources and my own. I tr y to
select the question that most likely would be asked and what is important to know.
Here they are.
. . .
1. W hat is Python?
The benefits of pythons are that it is simple and easy, portable, extensible, build-in
data structure and it is open-source.
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.
Memor y in Python is managed by Python private heap space. All Python objects
and data structures are located in a private heap. This private heap is taken
care of by Python Interpreter itself, and a programmer doesn’t have access to
this private heap.
Python memor y manager takes care of the allocation of Python private heap
space.
Memor y for Python private heap space is made available by Python’s in-built
garbage collector, which recycles and frees up all the unused memor y.
6. W hat is pep 8?
PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to
format Python code for maximum readability.
#Comment Example
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 ver y good shortcut method to comment on
multiple lines. All you need to do is hold the ctrl key and left-click in ever y place
wherever you want to include a # character and type a # just once. This will
comment on 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, ser ve the purpose of comments as well.
"""
This is Docstring example
It is useful for documentation purposes
"""
10. Is indentation optional in Python?
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 compulsor y.
def example(a):
return a*2
Global Variables:
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.
A lambda form in python does not have statements as it is used to make new
function object and then return them at runtime.
String
List
Tuple
Dictionar y
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.
17. W hat are negative indexes and why are they used?
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.
#Example of Dictionary
You could access the values in a dictionar y by indexing using the key. Indexing is
presented by [] .
#Accessing Dictionary
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. The list is defined using [] and tuple
defined using () .
#List
list_ex = [1,2,'test']
#List is mutable
list_ex[0] = 100
#Tuple
tuple_ex = (1,2,'test)
In Python, iterators are used to iterate a group of elements, containers like the list
or string. By iteration, it means that it could be looped by using a statement.
#Reverse example
The Ternar y operator is the operator that is used to show the conditional
statements. This consists of true or false values with a statement that has to be
evaluated for it.
The break statement allows loop termination when some condition is met and the
control is transferred to the next statement.
#Break example
for i in range(5):
if i < 3:
print(i)
else:
break
The pass statement in Python is used when a statement is required syntactically but
you do not want any command or code to execute.
#Pass example
for i in range(10):
if i%2 == 0:
print(i)
else:
pass
The map() function is a function that takes a function as an argument and then
applies that function to all the elements of an iterable, passed to it as another
argument. It would return a map object so we need to transform it to a list object.
number_list = [2,3,4,5]
print(list(map(number_exponential, number_list)))
#Enumerate example
They are syntax constructions to ease the creation of a Dictionar y or List based on
existing iterable. It is created by looping inside the Dictionar y or List object.
#Dictionary comprehension
#List comprehension
Slicing is a mechanism to select a range of items from sequence types like list, tuple,
strings, etc. This slicing is done by indexing method.
#Slicing example
list_example = [1,2,3,4,'test','test2']
print(list_example[1:4])
print(not 1 == 2)
It is a Floor Division operator, which is used for dividing two operands with the
result showing only digits before the decimal point.
print(5//2)
You can do it by using .append() attribute that list has. By passing any values to the
.append() attribute, the new value would be placed at the end of the list sequence.
list_example = [1,2,3,4,5]
list_example.append(6)
print(list_example)
Shallow copy is used when a new instance type gets created and it keeps the values
that are copied in the new instance. Shallow copy is used to copy the reference
pointers just like it copies the values. It means when we copying an object to
another variable, it would be connected.
list_example = [1,2,3,4,5]
another_list = list_example
another_list[0] = 100
print(list_example)
Deep copy is used to store the values that are already copied. The deep copy doesn’t
copy the reference pointers to the objects. It makes the reference to an object and
the new object that is pointed by some other object gets stored. Contrast with a
shallow copy, The changes made in the original copy won’t affect any other copy
that uses the object. It means they are not connected.
list_example = [1,2,3,4,5]
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.
class sample:
pass
test=sample()
test.name="test1"
print(test.name)
38. W ill the do-while loop work if you don’t end it with a semicolon?
This is a Trick question! Python does not support an intrinsic do-while loop.
Secondly, to terminate do-while loops is a necessity for languages like C++.
In this case, we could use a .join() attribute from the string object. Here we passed
the list object to the attribute.
print('me' in 'membership')
print('mes' not in 'membership')
Identity operators is an operator that tell us if two values have the same identity.
The operators are ‘is’ and ‘is not’.
It would return an iterator of tuples. It would form an n-pair of value from iterable
passed on the function. The n is the number of iterable passed on the function.
44. W hat is the difference if range() function takes one argument, two
arguments, and three arguments?
When we pass only one argument, it takes it as the stop value. Here, the start value
is 0, and the step value is +1. The iteration with a range would always stop 1 value
before the stop value.
for i in range(5):
print(i)
When we pass two arguments, the first one is the start value, and the second is the
stop value.
for i in range(1,5):
print(i)
Using three arguments, the first argument is the start value, the second is the stop
value, and the third is the step value.
for i in range(1,10,2):
print(i)
45. W hat is the best code you can write to swap two numbers?
a = 1
b = 2
#Swab number
a, b = b, a
46. How can you declare multiple assignments in one line of code?
There are two ways to do this. First is by separately declare the variable in the same
line.
a, b, c = 1,2,3
Another way is by declaring the variable in the same line with only one value.
a=b=c=1
The with statement in Python ensures that cleanup code is executed when working
with unmanaged resources by encapsulating common preparation and cleanup
tasks. It may be used to open a file, do something, and then automatically close the
file at the end. It may be used to open a database connection, do some processing,
then automatically close the connection to ensure resources are closed and
available for others. with will cleanup the resources even if an exception is thrown.
The tr y-except block is commonly used when we want something to execute when
errors were raised. The except block is executed when the code in the tr y block has
encountered an error.
a = (1,2,3)
try:
a[0] = 2
except:
print('There is an error')
For simple repetitive looping and when we don’t need to iterate through a list of
items- like database records and characters in a string.
Modules are independent Python scripts with the .py extension that can be reused in
other Python codes or scripts using the import statement. A module can consist of
functions, classes, and variables, or some runnable code. Modules not only help in
keeping Python codes organized but also in making codes less complex and more
efficient.
Write-only mode(‘w’): Open a file for writing. If the file contains data, data
would be lost. Another new file is created.
Read-Write mode(‘r w’): Open a file for reading, write mode. It means updating
mode.
Append mode(‘a’): Open for writing, append to the end of the file, if the file
exists.
Pickle module accepts any Python object and converts it into a string representation
and dumps it into a file by using a dump function, this process is called pickling.
While the process of retrieving original Python objects from the stored string
representation is called unpickling.
import pickle
a = 1
#Pickling process
pickle.dump(a, open('file.sav', 'wb'))
#Unpickling process
file = pickle.load(open('file.sav', 'rb'))
We use python NumPy array instead of a list because of the below three reasons:
1. Less Memor y
2. Fast
3. Convenient
import numpy as np
print(p)
57. How do you get the current working directory using Python?
Working with Python, you may need to read and write files from various directories.
To find out which director y we’re presently working under, we can use the getcwd()
method from the os module.
import os
os.getcwd()
58. W hat do you see below? W hat would happen if we execute it?
a = '1'
b = '2'
c = '3'
This is string concatenation. If even one of the variables isn’t a string, this would
raise a TypeError. What would happen is that we get an output of the string
concatenation.
Casting is when we convert a variable value from one type to another. In Python, it
could be done with functions such as list(),int(), float() or str() . An example is
when you convert a string into an integer object.
a = '1'
b = int(a)
In the above code, we tr y to import a non-exist function from the numpy module.
That is why we getting an error.
We could use the del() function to remove or unsign a variable. This is considered a
good practice to remove all the unnecessar y variables when we are not using it.
a = 1
del a
Both append() and extend() methods are methods used to add elements at the end
of a list.
extend(another-list): Adds the elements of another list at the end of the list
import sys
sys.version
66. W hat does this mean: *args, **kwargs? And why would we use it?
We use *args when we aren’t sure how many arguments are going to be passed to a
function, or if we want to pass a stored list or tuple of arguments to a function.
**kwargs is used when we don’t know how many keyword arguments will be passed
to a function, or it can be used to pass the values of a dictionar y as keyword
arguments. The identifiers args and kwargs are optional, as you could change it to
another name such as *example **another but it is better to just use the default
name.
#Example of *args
def sample(*args):
print(args)
sample('time', 1, True)
#Example of **kwargs
def sample(**kwargs):
print(kwargs)
sample(a = 'time', b = 1)
67. W hat is help() and dir() functions in Python?
The help() function displays the documentation string and helps for its argument.
import numpy
help(numpy.array)
import numpy
dir(numpy.array)
Double Underscore (Name Mangling) — Any identifier of the form __spam (at least
two leading underscores, at most one trailing underscore) is textually replaced with
_classname__spam, where the class name is the current class name with a leading
underscore(s) stripped. This mangling is done without regard to the syntactic
position of the identifier, so it can be used to define class-private instance and class
variables, methods, variables stored in globals, and even variables stored in
instances. private to this class on instances of other classes.
ss = “Python Programming!”
print(ss[5])