Q-1: What Is Python, What Are The Benefits of Using It, and What Do You Understand of PEP 8?
Q-1: What Is Python, What Are The Benefits of Using It, and What Do You Understand of PEP 8?
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
However, the flow is like that a new list gets created once after the function is defined.
And the same get used whenever someone calls the extendList method without a list
argument. It works like this because the calculation of expressions (in default
arguments) occurs at the time of function definition, not during its invocation.
The list1 and list3 are hence operating on the same default list, whereas list2 is running
on a separate object that it has created on its own (by passing an empty list as the
value of the list parameter).
The definition of the extendList function can get changed in the following manner.
list1 = [10]
list2 = [123]
list3 = ['a']
Q-3: What Is The Statement That Can Be Used In Python If The
Program Requires No Action But Requires It Syntactically?
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.
import os
print (os.path.expanduser('~'))
Output:
/home/runner
Q-5: What Are The Built-In Types Available In Python?
Here is the list of most commonly used built-in types that Python supports:
Check out the “re” expression that can check the email id for .com and .co.in
subdomain.
import re
print(re.search(r"[0-9a-zA-Z.]+@[a-zA-
Z]+\.(com|co\.in)$","micheal.pages@mp.com"))
Q-12: What Do You Think Is The Output Of The Following Code
Fragment? Is There Any Error In The Code?
list = ['a', 'b', 'c', 'd', 'e']
print (list[10:])
The result of the above lines of code is []. There won’t be any error like an IndexError.
You should know that trying to fetch a member from the list using an index that exceeds
the member count (for example, attempting to access list[10] as given in the question)
would yield an IndexError. By the way, retrieving only a slice at the starting index that
surpasses the no. of items in the list won’t result in an IndexError. It will just return an
empty list.
Q-13: Is There A Switch Or Case Statement In Python? If Not
Then What Is The Reason For The Same?
No, Python does not have a Switch statement, but you can write a Switch function and
then use it.
for i in range(5):
print(i)
The range() function accompanies two sets of parameters.
range(stop)
stop: It is the no. of integers to generate and starts from zero. eg. range(3) ==
[0, 1, 2].
range([start], stop[, step])
Start: It is the starting no. of the sequence.
Stop: It specifies the upper limit of the sequence.
Step: It is the incrementing factor for generating the sequence.
Points to note:
Only integer arguments are allowed.
Parameters can be positive or negative.
The range() function in Python starts from the zeroth index.
Q-15: What Are The Optional Statements Possible Inside A Try-
Except Block In Python?
There are two optional clauses you can use in the try-except block.
The “else” clause
It is useful if you want to run a piece of code when the try block doesn’t create
an exception.
The “finally” clause
It is useful when you want to execute some steps which run, irrespective of
whether there occurs an exception or not.
Q-16: What Is A String In Python?
A string in Python is a sequence of alpha-numeric characters. They are immutable
objects. It means that they don’t allow modification once they get assigned a value.
Python provides several methods, such as join(), replace(), or split() to alter strings. But
none of these change the original object.
Q-17: What Is Slicing In Python?
Slicing is a string operation for extracting a part of the string, or some part of a list. In
Python, a string (say text) begins at index 0, and the nth character stores at position
text[n-1]. Python can also perform reverse indexing, i.e., in the backward direction, with
the help of negative numbers. In Python, the slice() is also a constructor function which
generates a slice object. The result is a set of indices mentioned by range(start, stop,
step). The slice() method allows three parameters. 1. start – starting number for the
slicing to begin. 2. stop – the number which indicates the end of slicing. 3. step – the
value to increment after each index (default = 1).
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.
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.
In Python, strings are also lists of characters. We can access them using the index
which begins from zero and goes to the length minus one.
For example, in the string “Program,” the indexing happens like this:
Program 0 1 2 3 4 5
Q-21: What Is Docstring In Python?
A docstring is a unique text that happens to be the first statement in the following
Python constructs:
Module, Function, Class, or Method definition.
Python has given us many built-in functions such as print() and provides the ability to
create user-defined functions.
1. Built-in, and
2. User-defined.
The built-in functions happen to be part of the Python language. Some of these are
print(), dir(), len(), and abs() etc.
Step-1: to begin the function, start writing with the keyword def and then mention the
function name.
Step-2: We can now pass the arguments and enclose them using the parentheses. A
colon, in the end, marks the end of the function header.
Step-3: After pressing an enter, we can add the desired Python statements for
execution.
The return is a Python statement which we can use in a function for sending a value
back to its caller.
Python will treat that variable as local in the function-level scope. Any changes made to
that variable will remain local and will not reflect outside the function.
This scheme also has the advantage of bringing more time and space efficiency
because it leaves the need for creating local copies.
On the contrary, the disadvantage could be that a variable can get changed accidentally
during a function call. Hence, the programmers need to handle in the code to avoid
such uncertainty.
The continue statement is applicable for both the “while” and “for” loops.
Signature: id(object)
It accepts one parameter and returns a unique identifier associated with the input
object.
Please note that this type of argument syntax doesn’t allow passing a named argument
to the function.
I
am
Learning
Python
Q-34: What Does The **Kwargs Do In Python?
We can also use the **kwargs syntax in a Python function declaration. It let us pass N
(variable) number of arguments which can be named or keyworded.
Since Python is interpreter-based, so it sequentially executes the lines of the code one-
by-one.
Python also does have a Main() method. But it gets executed whenever we run our
Python script either by directly clicking it or starts it from the command line.
We can also override the Python default main() function using the Python if statement.
Please see the below code.
print("Welcome")
print("__name__ contains: ", __name__)
def main():
print("Testing the main function")
if __name__ == '__main__':
main()
The output:
Welcome
__name__ contains: __main__
Testing the main function
Q-36: What Does The __ Name __ Do In Python?
The __name__ is a unique variable. Since Python doesn’t expose the main() function,
so when its interpreter gets to run the script, it first executes the code which is at level 0
indentation.
To see whether the main() gets called, we can use the __name__ variable in an if
clause compares with the value “__main__.”
The break statement in a nested loop causes the control to exit from the inner iterative
block.
It returns the string denoting a character whose Unicode code point is an integer.
For example, the chr(122) returns the string ‘z’ whereas the chr(1212) returns the string
‘Ҽ’.
>>> ord("z")
122
Q-43: What Is Rstrip() In Python?
Python provides the rstrip() method which duplicates the string but leaves out the
whitespace characters from the end.
The rstrip() escapes the characters from the right end based on the argument value,
i.e., a string mentioning the group of characters to get excluded.
str.rstrip([char sequence/pre>
#Example
test_str = 'Programming '
# The trailing whitespaces are excluded
print(test_str.rstrip())
Q-44: What Is Whitespace In Python?
Whitespace represents the characters that we use for spacing and separation.
It returns True if all characters in the string are of alphabet type, else it returns False.
#Example
str = 'pdf csv json'
print(str.split(" "))
print(str.split())
The output:
#Example
str = 'lEaRn pYtHoN'
print(str.title())
The output:
Learn Python
Now, check out some general purpose Python interview questions.
The tests confirmed that PyPy is nearly five times faster than the CPython. It currently
supports Python 2.7.
For example, many of the Python operations execute as atomic such as calling the
sort() method on a list.
This heap manager does the allocation/de-allocation of heap space for objects.
Also, the tuples use parentheses for enclosing, but the lists have square brackets in
their syntax.
The collection is a set of keys having a single associated value. We can call it a hash, a
map, or a hashmap as it gets called in other programming languages.
They are mutable and hence will not change. The values associated with the keys can
be of any Python types.
Internally, it has a contiguous array for referencing to other objects and stores a pointer
to the array variable and its length in the list head structure.
We can make it by using the keyword “class.” An object gets created from the
constructor. This object represents the instance of the class.
The code which is common will rest in the base class, and the other object will now
inherit from the parent class. Check out the below example.
desk = Desktop()
print(desk.processor, desk.os, desk.ram)
lap = Laptop()
print(lap.processor, lap.os, lap.ram)
The output:
def get_PC(self):
return "%s cpu & %s ram" % (self.processor, self.ram)
class Tablet():
make = "Intel"
def __init__(self, processor, ram, make):
self.PC = PC(processor, ram) # Composition
self.make = make
def get_Tablet(self):
return "Tablet with %s CPU & %s ram by %s" %
(self.PC.processor, self.PC.ram, self.make)
if __name__ == "__main__":
tab = Tablet("i7", "16 GB", "Intel")
print(tab.get_Tablet())
The output is:
On the contrary, exceptions happen due to the occurrence of an external event which
interrupts the normal flow of the program.
Q-65: How Do You Handle Exceptions With Try/Except/Finally In
Python?
Python lay down Try, Except, Finally constructs to handle errors as well as Exceptions.
We enclose the unsafe code indented under the try block. And we can keep our fall-
back code inside the except block. Any instructions intended for execution last should
come under the finally block.
try:
print("Executing code in the try block")
print(exception)
except:
print("Entering in the except block")
finally:
print("Reached to the final block")
The output is:
For example, if we want the user to enter only odd numbers, else will raise an
exception.
Python library has a no. of iterators. For example, a list is also an iterator and we can
start a for loop over it.
print(next(generate()))
The output is:
In the example below, we’ve written a simple closure for multiplying numbers.
def multiply_number(num):
def product(number):
'product() here is a closure'
return num * number
return product
num_2 = multiply_number(2)
print(num_2(11))
print(num_2(24))
num_6 = multiply_number(6)
print(num_6(1))
The output is:
22
48
6
Q-71: What Are Decorators In Python?
Python decorator gives us the ability to add new behavior to the given objects
dynamically. In the example below, we’ve written a simple example to display a
message pre and post the execution of a function.
def decorator_sample(func):
def decorator_hook(*args, **kwargs):
print("Before the function call")
result = func(*args, **kwargs)
print("After the function call")
return result
return decorator_hook
@decorator_sample
def product(x, y):
"Function to multiply two numbers."
return x * y
print(product(3, 3))
The output is:
However, we can take values of any kind. For distinguishing the data pairs, we can use
a comma(“,”) and keep the whole stuff inside curly braces({…}).
The enumerate() function attaches a counter variable to an iterable and returns it as the
“enumerated” object.
We can use this object directly in the “for” loops or transform it into a list of tuples by
calling the list() method. It has the following signature:
enumerate(iterable, to_begin=0)
Arguments:
iterable: array type object which enables iteration
to_begin: the base index for the counter is to get started, its
default value is 0
# Example - enumerate function
alist = ["apple","mango", "orange"]
astr = "banana"
print(list(enumerate(alist)) )
# Move the starting index to two from zero
print(list(enumerate(astr, 2)))
The output is:
All the information in this table remains in the global scope of the program and Python
allows us to retrieve it using the globals() method.
Signature: globals()
Arguments: None
# Example: globals() function
x = 9
def fn():
y = 3
z = y + x
# Calling the globals() method
z = globals()['x'] = z
return z
# Test Code
ret = fn()
print(ret)
The output is:
12
Q-84: Why Do You Use The Zip() Method In Python?
The zip method lets us map the corresponding index of multiple containers so that we
can use them using as a single unit.
Signature:
zip(*iterators)
Arguments:
Python iterables or collections (e.g., list, string, etc.)
Returns:
A single iterator object with combined mapped values
# Example: zip() function
But the instance or non-static variables are altogether different for different objects.
The programming languages like C++ and Java need to use the static keyword to make
a variable as the class variable. However, Python has a unique way to declare a static
variable.
All names initialized with a value in the class declaration becomes the class variables.
And those which get assigned values in the class methods becomes the instance
variables.
# Example
class Test:
aclass = 'programming' # A class variable
def __init__(self, ainst):
self.ainst = ainst # An instance variable
print(test1.aclass)
print(test2.aclass)
print(test1.ainst)
print(test2.ainst)
programming
programming
1
2
programming
Let’s now answer some advanced-level Python interview questions.
Q-86: How Does The Ternary Operator Work In Python?
The ternary operator is an alternative for the conditional statements. It combines true or
false values with a statement that you need to test.
copy.copy() function
It makes a copy of the file from source to destination.
It’ll return a shallow copy of the parameter.
copy.deepcopy() function
It also produces the copy of an object from the source to destination.
It’ll return a deep copy of the parameter that you can pass to the function.
Q-89: What Is The Purpose Of Doc Strings In Python?
In Python, the doc string is what we call as the doc strings. It sets a process of
recording Python functions, modules, and classes.
def demo2():
print 'in demo2()'
def demo1():
print 'in demo1()'
demo2()
sys.settrace(trace_calls)
demo1()
Q-95: Why And When Do You Use Generators In Python?
A generator in Python is a function which returns an iterable object. We can iterate on
the generator object using the yield keyword. But we can only do that once because
their values don’t persist in memory, they get the values on the fly.
Generators give us the ability to hold the execution of a function or a step as long as we
want to keep it. However, here are a few examples where it is beneficial to use
generators.
We can replace loops with generators for efficiently calculating results involving
large data sets.
Generators are useful when we don’t want all the results and wish to hold back for
some time.
Instead of using a callback function, we can replace it with a generator. We can
write a loop inside the function doing the same thing as the callback and turns it into
a generator.
Q-96: What Does The Yield Keyword Do In Python?
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.
See the example below.
def testgen(index):
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
yield weekdays[index]
yield weekdays[index+1]
day = testgen(0)
print next(day), next(day)
But remember, we can’t change the list after turning it into a tuple because it becomes
immutable.
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsTuple = tuple(weekdays)
print(listAsTuple)
Set doesn’t allow duplicate entries so that the conversion will remove any such
item.
A set is an ordered collection, so the order of list items would also change.
However, we can use the set() function to convert a list into a Set.
weekdays =
['sun','mon','tue','wed','thu','fri','sat','sun','tue']
listAsSet = set(weekdays)
print(listAsSet)
However, we can achieve the conversion by breaking the list into a set of pairs and then
call the zip() function to return them as tuples.
Passing the tuples into the dict() function would finally turn them into a dictionary.
weekdays = ['sun','mon','tue','wed','thu','fri']
listAsDict = dict(zip(weekdays[0::2], weekdays[1::2]))
print(listAsDict)
In Python, the list has a count() function which returns the occurrences of a particular
item.
Count The Occurrences Of An Individual Item.
weekdays =
['sun','mon','tue','wed','thu','fri','sun','mon','mon']
print(weekdays.count('mon'))
#output: 3
Count The Occurrences Of Each Item In The List.
We’ll use the list comprehension along with the count() method. It’ll print the frequency
of each of the items.
weekdays =
['sun','mon','tue','wed','thu','fri','sun','mon','mon']
print([[x,weekdays.count(x)] for x in set(weekdays)])
Also, the NumPy arrays are superior to the built-in lists. There are a no. of reasons for
this.