Web Technologies MCQs
Web Technologies MCQs
<DS>
<DD>
<LL>
<DL>
Answer: <DL>
4. Which method of the Component class is used to set the position and size of a component
in JSP?
setSize()
setBounds() method
setPosition()
setPositionSize()
Answer: setBounds() method
8. The tag used to create a hypertext relationship between current document and another
URL is___________
<LINK>
<A>
<ISINDEX>
None
Answer: <LINK>
18. Correct HTML to left align the content inside a table cell is____________
<td leftalign>
<td align = “left”>
<td raligh = “left” >
<tdleft>
Answer: <td align = “left”>
19. In ASP the function which returns an expression formatted as a date or time
is_________
FormatDateOrTime()
FormatTimeDate()
FormatDateTime()
FormatDateAndTime()
Answer: FormatDateTime()
22. Which of the following statements is incorrect regarding multimedia on the web?
The MPEG, AU and MIDI are cross-platform formats
The SND format has a relatively low fidelity
The MPEG, AIFF and WAV are cross-platform formats
VRML can be used to model and display 3D interactive graphics
Answer: The MPEG, AIFF and WAV are cross-platform formats
23. The web standard allows programmers on many different computer platforms to
dispersed format and display the information server. These programs are
called___________
Internet Explorer
Web Browsers
HTML
None
Answer: Web Browsers
24. What value does readLine() return when it has reached the end of a file in JSP?
False
Null
EOF
Last character in the file
Answer: Null
25. In JSP, the classes that allow primitive types to be accessed as objects are known
as________
Object classes
Primitive classes
Wrapper classes
Boxing classes
Answer: Wrapper classes
28. Any part of the graphic that is not included in another hot zone is considered to be part
of__________
Point
default
Rect
Polygon
Answer: Default
Python
1. What is Python? What are the benefits of using Python.
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.
Benefits of using Python:
Python is a general-purpose programming language that has a simple, easy-to-learn syntax that
emphasizes readability and therefore reduces the cost of program maintenance. Moreover, the
language is capable of scripting, is completely open-source, and supports third-party packages
encouraging modularity and code reuse.
Its high-level data structures, combined with dynamic typing and dynamic binding, attract a huge
community of developers for Rapid Application Development and deployment.
2. What is a dynamically typed language?
Before we understand a dynamically typed language, we should learn about what typing
is. Typing refers to type-checking in programming languages. In a strongly-typed language,
such as Python, "1" + 2 will result in a type error since these languages don't allow for "type-
coercion" (implicit conversion of data types). On the other hand, a weakly-typed language, such
as Javascript, will simply output "12" as result.
Type-checking can be done at two stages -
Static - Data Types are checked before execution.
Dynamic - Data Types are checked during execution.
Python is an interpreted language, executes each statement line by line and thus type-checking is
done on the fly, during execution. Hence, Python is a Dynamically Typed Language.
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.
Note: Local scope objects can be synced with global scope objects using keywords such
as global.
6. What are lists and tuples? What is the key difference between the two?
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).
But what is the real difference between the two? The key difference between the two is that
while lists are mutable, tuples on the other hand are immutable objects. This means that lists
can be modified, appended or sliced on the go but tuples remain constant and cannot be modified
in any manner. You can run the following example on Python IDLE to confirm the difference:
my_tuple = ('sara', 6, 5, 0.97)
my_list = ['sara', 6, 5, 0.97]
print(my_tuple[0]) # output => 'sara'
print(my_list[0]) # output => 'sara'
my_tuple[0] = 'ansh' # modifying tuple => throws an error
my_list[0] = 'ansh' # modifying list => list modified
print(my_tuple[0]) # output => 'sara'
print(my_list[0]) # output => 'ansh'
None Type:
None keyword represents the null values in Python. Boolean equality operation can be performed
using these NoneType objects.
Numeric Types:
There are three distinct numeric types - integers, floating-point numbers, and complex
numbers. Additionally, booleans are a sub-type of integers.
Class Name Description
int Stores integer literals including hex, octal and binary numbers as integers
complex Stores complex numbers in the form (A + Bj) and has attributes: real and imag
Note: The standard library also includes fractions to store rational numbers and decimal to store
floating-point numbers with user-defined precision.
Sequence Types:
According to Python Docs, there are three basic Sequence Types - lists,
tuples, and range objects. Sequence types have the in and not in operators defined for their
traversing their elements. These operators share the same priority as the comparison operations.
Note: The standard library also includes additional types for processing:
1. Binary data such as bytearray bytes memoryview , and
2. Text strings such as str.
Mapping Types:
A mapping object can map hashable values to random objects in Python. Mappings objects are
mutable and there is currently only one standard mapping type, the dictionary.
Set Types:
Currently, Python has two built-in set types - set and frozenset. set type is mutable and supports
methods like add() and remove(). frozenset type is immutable and can't be modified after
creation.
Note: set is mutable and thus cannot be used as key for a dictionary. On the other
hand, frozenset is immutable and thus, hashable, and can be used as a dictionary key or as an
element of another set.
Modules:
Module is an additional built-in type supported by the Python Interpreter. It supports one special
operation, i.e., attribute access: mymod.myobj, where mymod is a module
and myobj references a name defined in m's symbol table. The module's symbol table resides in
a very special attribute of the module __dict__, but direct assignment to this module is neither
possible nor recommended.
Callable Types:
Callable types are the types to which function call can be applied. They can be user-defined
functions, instance methods, generator functions, and some other built-in functions,
methods and classes.
Refer to the documentation at docs.python.org for a detailed view of the callable types.
def myEmptyFunc():
# do nothing
pass
myEmptyFunc() # nothing happens
## Without the pass keyword
# File "<stdin>", line 3
# IndentationError: expected an indented block
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.
Note: You can technically import the package as well, but alas, it doesn't import the modules
within the package to the local namespace, thus, it is practically useless.
# class definition
class Student:
def __init__(self, fname, lname, age, section):
self.firstname = fname
self.lastname = lname
self.age = age
self.section = section
# creating a new object
stu1 = Student("Sara", "Ansh", 22, "A2")
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.
pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3]
for p in pat:
pass
if (p == 0):
current = p
break
elif (p % 2 == 0):
continue
print(p) # output => 1 3 1 3 1
print(current) # output => 0
17. Explain how can you make a Python Script executable on Unix?
Script file must begin with #!/usr/bin/env python
import array
a = array.array('i', [1, 2, 3])
for i in a:
print(i, end=' ') #OUTPUT: 1 2 3
a = array.array('i', [1, 2, 'string']) #OUTPUT: TypeError: an integer is required (got type str)
a = [1, 2, 'string']
for i in a:
print(i, end=' ') #OUTPUT: 1 2 string
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.
38. What are negative indexes and why are they used?
Negative indexes are the indexes from the end of the list or tuple or string.
Arr[-1] means the last element of array Arr[]
arr = [1, 2, 3, 4, 5, 6]
#get the last element
print(arr[-1]) #output 6
#get the second last element
print(arr[-2]) #output 5
Python OOPS Interview Questions
def introduce(self):
print("Hello I am " + self.emp_name)
The self parameter in the init and introduce functions represent the reference to the current class
instance which is used for accessing attributes and methods of that class. The self parameter has
to be the first parameter of any method defined inside the class. The method of the class
InterviewbitEmployee can be accessed as shown below:
emp_1.introduce()
The overall program would look like this:
class InterviewbitEmployee:
def __init__(self, emp_name):
self.emp_name = emp_name
def introduce(self):
print("Hello I am " + self.emp_name)
# Child class
class ChildClass(ParentClass):
def child_func(self):
print("I am child class function")
# Driver code
obj1 = ChildClass()
obj1.par_func()
obj1.child_func()
Multi-level Inheritance: The members of the parent class, A, are inherited by child class which
is then inherited by another child class, B. The features of the base class and the derived class are
further inherited into the new derived class, C. Here, A is the grandfather class of class C.
# Parent class
class A:
def __init__(self, a_name):
self.a_name = a_name
# Intermediate class
class B(A):
def __init__(self, b_name, a_name):
self.b_name = b_name
# invoke constructor of class A
A.__init__(self, a_name)
# Child class
class C(B):
def __init__(self,c_name, b_name, a_name):
self.c_name = c_name
# invoke constructor of class B
B.__init__(self, b_name, a_name)
def display_names(self):
print("A name : ", self.a_name)
print("B name : ", self.b_name)
print("C name : ", self.c_name)
# Driver code
obj1 = C('child', 'intermediate', 'parent')
print(obj1.a_name)
obj1.display_names()
Multiple Inheritance: This is achieved when one child class derives members from more than
one parent class. All features of parent classes are inherited in the child class.
# Parent class1
class Parent1:
def parent1_func(self):
print("Hi I am first Parent")
# Parent class2
class Parent2:
def parent2_func(self):
print("Hi I am second Parent")
# Child class
class Child(Parent1, Parent2):
def child_func(self):
self.parent1_func()
self.parent2_func()
# Driver's code
obj1 = Child()
obj1.child_func()
Hierarchical Inheritance: When a parent class is derived by more than one child class, it is
called hierarchical inheritance.
# Base class
class A:
def a_func(self):
print("I am from the parent class.")
# Driver's code
obj1 = B()
obj2 = C()
obj1.a_func()
obj1.b_func() #child 1 method
obj2.a_func()
obj2.c_func() #child 2 method
class Child(Parent):
# Constructor
def __init__(self, name, age):
Parent.name = name
self.age = age
def display(self):
print(Parent.name, self.age)
# Driver Code
obj = Child("Interviewbit", 6)
obj.display()
By using super(): The parent class members can be accessed in child class using the super
keyword.
class Parent(object):
# Constructor
def __init__(self, name):
self.name = name
class Child(Parent):
# Constructor
def __init__(self, name, age):
'''
In Python 3.x, we can also use super().__init__(name)
'''
super(Child, self).__init__(name)
self.age = age
def display(self):
# Note that Parent.name cant be used
# here since super() is used in the constructor
print(self.name, self.age)
# Driver Code
obj = Child("Interviewbit", 6)
obj.display()
# protected members
_emp_name = None
_age = None
# private members
__branch = None
# constructor
def __init__(self, emp_name, age, branch):
self._emp_name = emp_name
self._age = age
self.__branch = branch
#public member
def display():
print(self._emp_name +" "+self._age+" "+self.__branch)
# introduce method
def introduce(self):
print('Hello, I am ', self.emp_name)
class Child(Parent):
pass
# Driver Code
print(issubclass(Child, Parent)) #True
print(issubclass(Parent, Child)) #False
We can check if an object is an instance of a class by making use of isinstance() method:
obj1 = Child()
obj2 = Parent()
print(isinstance(obj2, Child)) #False
print(isinstance(obj2, Parent)) #True
Python Pandas Interview Questions
52. Can you create a series from the dictionary object in pandas?
One dimensional array capable of storing different data types is called a series. We can create
pandas series from a dictionary object as shown below:
import pandas as pd
dict_info = {'key1' : 2.0, 'key2' : 3.1, 'key3' : 2.2}
series_obj = pd.Series(dict_info)
print (series_obj)
Output:
x 2.0
y 3.1
z 2.2
dtype: float64
If an index is not specified in the input method, then the keys of the dictionaries are sorted in
ascending order for constructing the index. In case the index is passed, then values of the index
label will be extracted from the dictionary.
53. How will you identify and deal with missing values in a dataframe?
We can identify if a dataframe has missing values by using the isnull() and isna() methods.
missing_data_count=df.isnull().sum()
We can handle missing values by either replacing the values in the column with 0 as follows:
df[‘column_name’].fillna(0)
Or by replacing it with the mean value of the column
df[‘column_name’] = df[‘column_name’].fillna((df[‘column_name’].mean()))
df = pd.DataFrame(data_info)
#To add new column third
df['third']=pd.Series([10,20,30],index=['a','b','c'])
print (df)
#To add new column fourth
df['fourth']=df['first']+info['third']
print (df)
56. How will you delete indices, rows and columns from a dataframe?
To delete an Index:
Execute del df.index.name for removing the index by name.
Alternatively, the df.index.name can be assigned to None.
For example, if you have the below dataframe:
Column 1
Names
John 1
Jack 2
Judy 3
Jim 4
To drop the index name “Names”:
df.index.name = None
# Or run the below:
# del df.index.name
print(df)
Column 1
John 1
Jack 2
Judy 3
Jim 4
To delete row/column from dataframe:
drop() method is used to delete row/column from dataframe.
The axis argument is passed to the drop method where if the value is 0, it indicates to drop/delete
a row and if 1 it has to drop the column.
Additionally, we can try to delete the rows/columns in place by setting the value of inplace to
True. This makes sure that the job is done without the need for reassignment.
The duplicate values from the row/column can be deleted by using the drop_duplicates() method.
57. Can you get items of series A that are not available in another series B?
This can be achieved by using the ~ (not/negation symbol) and isin() method as shown below.
import pandas as pd
df1 = pd.Series([2, 4, 8, 10, 12])
df2 = pd.Series([8, 12, 10, 15, 16])
df1=df1[~df1.isin(df2)]
print(df1)
"""
Output:
0 2
1 4
dtype: int64
"""
58. How will you get the items that are not common to both the given series A and B?
We can achieve this by first performing the union of both series, then taking the intersection of
both series. Then we follow the approach of getting items of union that are not there in the list of
the intersection.
63. You are given a numpy array and a new column as inputs. How will you delete the
second column and replace the column with a new column value?
Example:
Given array:
[[35 53 63]
[72 12 22]
[43 84 56]]
New Column values:
[
20
30
40
]
Solution:
import numpy as np
#inputs
inputArray = np.array([[35,53,63],[72,12,22],[43,84,56]])
new_col = np.array([[20,30,40]])
# delete 2nd column
arr = np.delete(inputArray , 1, axis = 1)
#insert new_col to array
arr = np.insert(arr , 1, new_col, axis = 1)
print (arr)
64. How will you efficiently load data from a text file?
We can use the method numpy.loadtxt() which can automatically read the file’s header and
footer lines and the comments if any.
This method is highly efficient and even if this method feels less efficient, then the data should
be represented in a more efficient format such as CSV etc. Various alternatives can be
considered depending on the version of NumPy used.
Following are the file formats that are supported:
Text files: These files are generally very slow, huge but portable and are human-readable.
Raw binary: This file does not have any metadata and is not portable. But they are fast.
Pickle: These are borderline slow and portable but depends on the NumPy versions.
HDF5: This is known as the High-Powered Kitchen Sink format which supports both PyTables
and h5py format.
.npy: This is NumPy's native binary data format which is extremely simple, efficient and
portable.
65. How will you read CSV data into an array in NumPy?
This can be achieved by using the genfromtxt() method by setting the delimiter as a comma.
from numpy import genfromtxt
csv_data = genfromtxt('sample_file.csv', delimiter=',')
66. How will you sort the array based on the Nth column?
For example, consider an array arr.
arr = np.array([[8, 3, 2],
[3, 6, 5],
[6, 1, 4]])
Let us try to sort the rows by the 2nd column so that we get:
[[6, 1, 4],
[8, 3, 2],
[3, 6, 5]]
We can do this by using the sort() method in numpy as:
import numpy as np
arr = np.array([[8, 3, 2],
[3, 6, 5],
[6, 1, 4]])
#sort the array using np.sort
arr = np.sort(arr.view('i8,i8,i8'),
order=['f1'],
axis=0).view(np.int)
We can also perform sorting and that too inplace sorting by doing:
arr.view('i8,i8,i8').sort(order=['f1'], axis=0)
67. How will you find the nearest value in a given numpy array?
We can use the argmin() method of numpy as shown below:
import numpy as np
def find_nearest_value(arr, value):
arr = np.asarray(arr)
idx = (np.abs(arr - value)).argmin()
return arr[idx]
#Driver code
arr = np.array([ 0.21169, 0.61391, 0.6341, 0.0131, 0.16541, 0.5645, 0.5742])
value = 0.52
print(find_nearest_value(arr, value)) # Prints 0.5645
68. How will you reverse the numpy array using one line of code?
This can be done as shown in the following:
reversed_array = arr[::-1]
where arr = original given array, reverse_array is the resultant after reversing all elements in the
input.
69. How will you find the shape of any given NumPy array?
We can use the shape attribute of the numpy array to find the shape. It returns the shape of the
array in terms of row count and column count of the array.
import numpy as np
arr_two_dim = np.array([("x1","x2", "x3","x4"),
("x5","x6", "x7","x8" )])
arr_one_dim = np.array([3,2,4,5,6])
# find and print shape
print("2-D Array Shape: ", arr_two_dim.shape)
print("1-D Array Shape: ", arr_one_dim.shape)
"""
Output:
2-D Array Shape: (2, 4)
1-D Array Shape: (5,)
"""
Python Libraries Interview Questions
71. What are some of the most commonly used built-in modules in Python?
Python modules are the files having python code which can be functions, variables or classes.
These go by .py extension. The most commonly available built-in modules are:
os
math
sys
random
re
datetime
JSON
72. What are lambda functions?
Lambda functions are generally inline, anonymous functions represented by a single expression.
They are used for creating function objects during runtime. They can accept any number of
parameters. They are usually used where functions are required only for a short period. They can
be used as:
mul_func = lambda x,y : x*y
print(mul_func(6, 4))
# Output: 24
74. Can you easily check if all characters in the given string is alphanumeric?
This can be easily done by making use of the isalnum() method that returns true in case the string
has only alphanumeric characters.
For Example -
"abdc1321".isalnum() #Output: True
"xyz@123$".isalnum() #Output: False
Another way is to use match() method from the re (regex) module as shown:
import re
print(bool(re.match('[A-Za-z0-9]+$','abdc1321'))) # Output: True
print(bool(re.match('[A-Za-z0-9]+$','xyz@123$'))) # Output: False
Based on the above diagram, there are three threads. First Thread acquires the GIL first and starts
the I/O execution. When the I/O operations are done, thread 1 releases the acquired GIL which is
then taken up by the second thread. The process repeats and the GIL are used by different threads
alternatively until the threads have completed their execution. The threads not having the GIL
lock goes into the waiting state and resumes execution only when it acquires the lock.
79. Are there any tools for identifying bugs and performing static analysis in python?
Yes, there are tools like PyChecker and Pylint which are used as static analysis and linting tools
respectively. PyChecker helps find bugs in python source code files and raises alerts for code
issues and their complexity. Pylint checks for the module’s coding standards and supports
different plugins to enable custom features to meet this requirement.
80. Differentiate between deep and shallow copies.
Shallow copy does the task of creating new objects storing references of original elements. This
does not undergo recursion to create copies of nested objects. It just copies the reference details
of nested objects.
Deep copy creates an independent and new copy of an object and even copies all the nested
objects of the original element recursively.
81. What is main function in python? How do you invoke it?
In the world of programming languages, the main is considered as an entry point of execution for
a program. But in python, it is known that the interpreter serially interprets the file line-by-line.
This means that python does not provide main() function explicitly. But this doesn't mean that
we cannot simulate the execution of main. This can be done by defining user-
defined main() function and by using the __name__ property of python file.
This __name__ variable is a special built-in variable that points to the name of the current
module. This can be done as shown below:
def main():
print("Hi Interviewbit!")
if __name__=="__main__":
main()
83. WAP (Write a program) which takes a sequence of numbers and check if all numbers
are unique.
You can do this by converting the list to set by using set() method and comparing the length of
this set with the length of the original list. If found equal, return True.
def check_distinct(data_list):
if len(data_list) == len(set(data_list)):
return True
else:
return False;
print(check_distinct([1,6,5,8])) #Prints True
print(check_distinct([2,2,5,5,7,8])) #Prints False
84. Write a program for counting the number of every character of a given text file.
The idea is to use collections and pprint module as shown below:
import collections
import pprint
with open("sample_file.txt", 'r') as data:
count_data = collections.Counter(data.read().upper())
count_value = pprint.pformat(count_data)
print(count_value)
85. Write a program to check and return the pairs of a given array A whose sum value is
equal to a target value N.
This can be done easily by using the phenomenon of hashing. We can use a hash map to check
for the current value of the array, x. If the map has the value of (N-x), then there is our pair.
def print_pairs(arr, N):
# hash set
hash_set = set()
86. Write a Program to add two integers >0 without using the plus operator.
We can use bitwise operators to achieve this.
def add_nums(num1, num2):
while num2 != 0:
data = num1 & num2
num1 = num1 ^ num2
num2 = data << 1
return num1
print(add_nums(2, 10))
87. Write a Program to solve the given equation assuming that a,b,c,m,n,o are constants:
ax + by = c
mx + ny = o
88. Write a Program to match a string that has the letter ‘a’ followed by 4 to 8 'b’s.
We can use the re module of python to perform regex pattern comparison here.
import re
def match_text(txt_data):
pattern = 'ab{4,8}'
if re.search(pattern, txt_data): #search for pattern in txt_data
return 'Match found'
else:
return('Match not found')
print(match_text("abc")) #prints Match not found
print(match_text("aabbbbbc")) #prints Match found
89. Write a Program to convert date from yyyy-mm-dd format to dd-mm-yyyy format.
We can again use the re module to convert the date string as shown below:
import re
def transform_date_format(date):
return re.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})', '\\3-\\2-\\1', date)
date_input = "2021-08-01"
print(transform_date_format(date_input))
90. Write a Program to combine two different dictionaries. While combining, if you find
the same keys, you can add the values of these same keys. Output the new dictionary.
We can use the Counter method from the collections module
from collections import Counter
d1 = {'key1': 50, 'key2': 100, 'key3':200}
d2 = {'key1': 200, 'key2': 100, 'key4':300}
new_dict = Counter(d1) + Counter(d2)
print(new_dict)